我知道在 Scala 3 中,現在可以使用Tuple.fromProductTyped
and在案例類實體和元組之間進行轉換summon[Mirror.Of].fromProduct
。
我希望能夠定義一個型別類,以證明可以使用上述方法將案例類T
轉換為和從該類轉換。(A, B)
我已經像這樣定義了型別類:
trait IsPair[T, A, B]:
def toTuple(t: T): (A, B)
def fromTuple(ab: (A, B)): T
我們如何IsPair
為任何符合條件的案例類派生?
推導到位后,以下內容應編譯并運行而不會出現錯誤:
case class Foo(a: Int, b: String)
val fooIsPair = summon[IsPair[Foo, Int, String]]
val foo = Foo(42, "qwerty")
val tuple = (42, "qwerty")
assert(fooIsPair.toTuple(foo) == tuple)
assert(fooIsPair.fromTuple(tuple) == foo)
uj5u.com熱心網友回復:
您可以只使用 aMirror
但將其限制為用于類似對的案例類:
import scala.deriving.Mirror
sealed trait IsPair[T]:
type A
type B
def toTuple(t: T): (A, B)
def fromTuple(ab: (A, B)): T
object IsPair:
type Aux[T, X, Y] = IsPair[T] { type A = X; type B = Y }
inline def apply[T](using ev: IsPair[T]): ev.type = ev
given instance[T <: Product, X, Y](using
ev: Mirror.Product { type MirroredType = T; type MirroredMonoType = T; type MirroredElemTypes = (X, Y) }
): IsPair[T] with
override final type A = X
override final type B = Y
override def toTuple(t: T): (X, Y) =
Tuple.fromProductTyped(t)
override def fromTuple(xy: (X, Y)): T =
ev.fromProduct(xy)
end IsPair
這樣我們就可以做到這一點:
val foo = Foo(42, "qwerty")
val tuple = (42, "qwerty")
val fooIsPair = IsPair[Foo]
assert(fooIsPair.toTuple(foo) == tuple)
assert(fooIsPair.fromTuple(tuple) == foo)
您可以看到這里運行的代碼。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/467641.html
上一篇:Sparkscala如何洗掉2個資料幀之間不共有的列
下一篇:Spark-將嵌套列更新為字串