在Scala 3中,我試圖從一個String的串列中實體化一個case類,例如
串列List("bob", "2.2", "1")適合Foo的欄位:
case class Foo(aString: String, aDouble: Double, aInt: Int)
而listStringTOclass[Foo](List("bob", "2.2", "1"))回傳Foo(bob,2.2,1)
但是我不能檢索到Foo元素的型別,在我的代碼中我寫了val types = List("String", "Double", "Int")但是我應該使用MirroredElemTypes來概括,有什么幫助嗎?
import scala.deriving.Mirror。
import scala.compiletime.summonAll
def listStringTOclass[A](stringValues。 List[String])(using m: Mirror.ProductOf[A]) = {
type TheType = String
type StringValue = String
val types = List("String", "Double", "Int") //m.MirroredElemTypes,應該是Type而不是string。
def valueList(ll: List[(TheType, StringValue)])。) List[Any] = ll match {
case Nil => Nil {
case h::t if h._2 == "String"/span> => h._1 :: valueList(t)
case h::t if h._2 == "Int" => h._1.toInt :: valueList(t)
case h::t if h._2 == "Double" => h._1.toDouble : : valueList(t)
case _ => ??
}
val tv: List[(TheType, StringValue)] = stringValues.zip( types)
val l: List[Any] = valueList(tv
println(l) // List(bob, 2.2, 1)/span>
val tuple。Tuple = l.foldRight[Tuple](EmptyTuple) (_ *: _)
println(tuple) // (bob,2.2,1)
m.fromProduct(tuple)
}
case class Foo(aString: String, aDouble: Double, aInt: Int)?
val o = listStringTOclass[Foo](List("Bob", "2. 2"/span>, "1"/span>)
println(o) //Foo(bob,2.2,1)。
uj5u.com熱心網友回復:
這樣做怎么樣(在scala 3.0.1中作業):
scala> object list2class{
| import scala.deriving.Mirror。
|
trait Decoder[A, B] extends (A => B)
| object Decoder。
| 給定 Decoder[String, String] = s => s
| 給定 Decoder[String, Int] = _.toInt
| 給定 Decoder[String, Double] = _.toDouble
|給定的解碼器[List[String], EmptyTuple] = {
| case Nil => EmptyTuple[/span>] =>
| case s => throw IllegalArgumentException(s.toString() )
| }
|給定 [H, T <: Tuple](using dh: 解碼器[String, H], dt: Decoder[List[String], T] )。) Decoder[List[String], H *: T] = {
| case h::t => dh(h) *: dt(t)
| case Nil => throw IndexOutOfBoundsException()
| }
|
def apply[A](xs: List[String])(using m: Mirror.ProductOf[A], d: Decoder[List[String], m.MirroredElemTypes] )。) A =
| m.fromProduct(d(xs))
| }
//定義物件list2class。
scala> case class Foo(aString: String, aDouble: Double, aInt: Int)?
//定義了案例類Foo。
scala> list2class[Foo](List("bob"/span>, "2.2", "1")
val res0: Foo = Foo(bob,2.2,1)
uj5u.com熱心網友回復:
考慮使用shapeless,通過HList "異質串列 "進行半自動的案例類推演。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/309132.html
標籤:
