我想为类和编码集合实现ItemEncoder
类型类Element
elements
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 {
???
}
}