在scala 3中,你可以使用Tuple.fromProductTyped從case類中獲得一個元組。
我想獲得嵌套案例類的所有欄位,例如:
我想獲得嵌套案例類的所有欄位。
case class Baz(x。String)。
case class Employee(name。Baz, number: Int, manager: Boolean)?
Tuple. fromProductTyped(Employee(Baz("hello"), 42, false) // (Baz(hello),42,false) but I need (hello,42,false).
下面的代碼試圖獲得嵌套的案例類的元組,但是在第***行失敗了
沒有implicit引數的 type deriving。 鏡面。 ProductOf[Product] was found。 title">發現 for parameter m of method fromProductTyped in object Tuple
val tuple2 = Tuple.fromProductTyped(x)
trait RowEncoder[A] {
def encodeRow(a: A)。List[String]
}
def tupleToCsv[A < 。Tuple: RowEncoder](tuple: A) 。List[String] = summon[RowEncoder[A]].encodeRow(tuple))
case class Baz(x: String)
case class Employee(name。Baz, number: Int, manager: Boolean)。
def flatTuple[A < 。Tuple](tuple: A) 。Tuple = {
tuple match {
case x *: xs =>
x match {
case x: Product =>
val tuple2 = Tuple.fromProductTyped(x) // ***
flatTuple(tuple2) flatTuple(xs)
case x => x *: flatTuple(xs)
}
case _ => EmptyTuple[/span
}
}
val tuple = Tuple. fromProductTyped(Employee(Baz("hello"), 42, false)
println(flatTuple(tuple)) //預期。(hello,42,false)
為了測驗,在第***行用Baz("hello")替換x
我怎樣才能解決這個問題呢?
uj5u.com熱心網友回復:
你必須使用Tuple.fromProduct(x)而不是Tuple.fromProductTyped(x):
def flatTuple[A < 。Tuple](tuple: A) 。Tuple = {
tuple match {
case x *: xs =>
x match {
case x: Product =>
val tuple2 = Tuple.fromProduct(x) // ***
flatTuple(tuple2) flatTuple(xs)
case x => x *: flatTuple(xs)
}
case _ => EmptyTuple[/span
}
}
uj5u.com熱心網友回復:
如果你不關心回傳元組的確切型別,下面的方法就足夠了:
scala> def flat(any: Any)。Tuple = any match
| case p。Product => p.productIterator.map(flat). foldLeft(EmptyTuple: Tuple) (_ _)
| case a => Tuple1(a)
|
def flat(any: Any)。Tuple(any: Any).
scala> val flatTuple = flat(Employee(Baz("hello")。42, false)
val flatTuple: Tuple = (hello,42, false)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/309109.html
標籤:
下一篇:在pyspark列內訪問名稱
