0

I want to implement ItemEncoder type class for Element class and encode elements collection

trait Tag
case class Element[A](attrName: String, value: A) extends Tag

val elements = Element("name", "foo") :: Element("age", 37) :: Element("married", true) :: HNil

trait ItemEncoder[A] {
  // labeled generic - field name and field value
  def encode(element: Element[A]): List[Item]
}

object ItemEncoder {
  def apply[A](implicit encoder: ItemEncoder[A]): ItemEncoder[A] = encoder

  def instance[A](f: Element[A] => List[Item]): ItemEncoder[A] =
    new ItemEncoder[A] {
      override def encode(element: Element[A]) = f(element)
    }
}

implicit val stringEncoder: ItemEncoder[String] =
  ItemEncoder.instance(element => {
    val item = new Item()
    item.setString(element.attrName, element.value)
    List(item)
  })

implicit val intEncoder: ItemEncoder[Int] =
  ItemEncoder.instance(element => {
    val item = new Item()
    item.setInt(element.attrName, element.value)
    List(item)
  })

implicit val booleanEncoder: ItemEncoder[Boolean] =
  ItemEncoder.instance(element => {
    val item = new Item()
    item.setBoolean(element.attrName, element.value)
    List(item)
  })

implicit def hlistEncoder[K, H, T <: HList](
  implicit
  hEncoder: ItemEncoder[H],
  tEncoder: ItemEncoder[T]
): ItemEncoder[Element[K] :: T] = {
  ItemEncoder.instance {
    ???
  }
}
iuriisusuk
  • 424
  • 5
  • 15
  • Do you want to be able to encode things like `Element[Element[Int] :: Element[String] :: HNil]`? – Jasper-M Feb 16 '17 at 11:43
  • @Jasper-M no, this should be a compile error! – iuriisusuk Feb 16 '17 at 12:12
  • Then I think that `hlistEncoder` either shouldn't be there or should be doing something entirely different than its interface is telling me right now. Maybe you could explain some more what exactly you're trying to do or show some examples of how you want to use it. – Jasper-M Feb 16 '17 at 12:20
  • I think the problem is that your `ItemEncoder` can only ever encode a single `Element` because that's fixed in its interface. – Jasper-M Feb 16 '17 at 12:23

0 Answers0