Reputation: 565
According to https://www.scala-lang.org/2021/02/26/tuples-bring-generic-programming-to-scala-3.html
I can write correctly:
def tupleToCsv[A <: Tuple : RowEncoder](tuple: A): List[String] = summon[RowEncoder[A]].encodeRow(tuple)
case class Employee(name: String, number: Int, manager: Boolean)
val t = Tuple.fromProductTyped(Employee("Bob", 42, false))
println(tupleToCsv(t)) // List(Bob, 42, false)
but I'd like write a unique method toCsv
def toCsv[A <: Product](t: A)(using m: scala.deriving.Mirror.ProductOf[A]): List[String] = {
val tuple = Tuple.fromProductTyped(t)
val aa = summon[RowEncoder[A]] // ***
aa.encodeRow(tuple)
}
and call it with toCsv(Employee("Bob", 42, false))
the compiler at row *** says:
no implicit argument of type RowEncoder[A] was found for parameter x of method summon in object Predef
where: A is a type in method toCsv with bounds <: Product
val aa = summon[RowEncoder[A]]
how can I provide automatic derivation for A ?
Upvotes: 4
Views: 310
Reputation: 1551
Here it is:
def toCsv[A <: Product](t: A)(using m: scala.deriving.Mirror.ProductOf[A], e: RowEncoder[m.MirroredElemTypes]): List[String] =
e.encodeRow(Tuple.fromProductTyped(t))
Upvotes: 2