gpt4 book ai didi

Scala 3 - 使用产品进行泛型编程

转载 作者:行者123 更新时间:2023-12-04 12:54:05 25 4
gpt4 key购买 nike

根据 https://www.scala-lang.org/2021/02/26/tuples-bring-generic-programming-to-scala-3.html
我可以正确写:

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)
但我想写一个独特的方法 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)
}
并用 toCsv(Employee("Bob", 42, false)) 调用它
第 *** 行的编译器说:
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]]
如何为 A 提供自动推导?

最佳答案

这里是:

def toCsv[A <: Product](t: A)(using m: scala.deriving.Mirror.ProductOf[A], e: RowEncoder[m.MirroredElemTypes]): List[String] =
e.encodeRow(Tuple.fromProductTyped(t))

关于Scala 3 - 使用产品进行泛型编程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69100575/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com