简体   繁体   English

Scala案例类参数从数组实例化

[英]Scala case class arguments instantiation from array

Consider a case class with a possibly large number of members; 考虑一个可能有大量成员的案例类; to illustrate the case assume two arguments, as in 为了说明这个案例假设两个论点,如

case class C(s1: String, s2: String)

and therefore assume an array with size of at least that many arguments, 因此假设一个大小至少为那么多参数的数组,

val a = Array("a1", "a2")

Then 然后

scala> C(a(0), a(1))
res9: C = c(a1,a2)

However, is there an approach to case class instantiation where there is no need to refer to each element in the array for any (possibly large) number of predefined class members ? 但是,是否存在一种案例类实例化方法,其中不需要为数组中的每个元素引用任何(可能是大量)预定义类成员?

No, you can't. 不,你不能。 You cannot guarantee your array size is at least the number of members of your case class. 您不能保证您的数组大小至少是您的案例类的成员数。

You can use tuples though. 你可以使用元组。

Suppose you have a mentioned case class and a tuple that looks like this: 假设您有一个提到的案例类和一个如下所示的元组:

val t = ("a1", "a2")

Then you can do: 然后你可以这样做:

c.tupled(t)

Having gathered bits and pieces from the other answers, a solution that uses Shapeless 2.0.0 is thus as follows, 从其他答案收集了点点滴滴之后,使用Shapeless 2.0.0的解决方案如下,

import shapeless._
import HList._
import syntax.std.traversable._

val a = List("a1", 2)                    // List[Any]
val aa = a.toHList[String::Int::HNil]
val aaa = aa.get.tupled                  // (String, Int)

Then we can instantiate a given case class with 然后我们可以实例化一个给定的case类

case class C(val s1: String, val i2: Int)
val ins = C.tupled(aaa)

and so 所以

scala> ins.s1
res10: String = a1

scala> ins.i2
res11: Int = 2

The type signature of toHList is known at compile time as much as the case class members types to be instantiate onto. toHList的类型签名在编译时是已知的,与要实例化的case类成员类型一样多。

To convert a Seq to a tuple see this answer: https://stackoverflow.com/a/14727987/2483228 要将Seq转换为元组,请参阅以下答案: https//stackoverflow.com/a/14727987/2483228

Once you have a tuple serejja's answer will get you to a c . 一旦你有一个元组serejja的答案会让你到一个c

Note that convention would have us spell c with a capital C . 请注意,惯例会让我们用大写C拼写c

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM