Scala class case arguments from an array

Consider a case class with as many members as possible; to illustrate the case, suppose two arguments, as in

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

and therefore accept an array of at least a few arguments,

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

Then

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

However, is there an approach to an instance of the case class when there is no need to refer to each element in the array for any (possibly large) number of predefined class members?

+4
source share
3 answers

Having collected pieces from other answers, the solution using Shapeless 2.0.0 looks as follows:

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 create an instance of the case class with

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

and therefore

scala> ins.s1
res10: String = a1

scala> ins.i2
res11: Int = 2

toHList , case, .

+3

, . , , , case.

.

, case , :

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

:

c.tupled(t)
+5

Seq , . : fooobar.com/questions/90208/...

, , , c.

, c c.

+3

Source: https://habr.com/ru/post/1530555/


All Articles