case class Foo(a: Int, b: Int, c: Int)
val s = Seq(1, 2, 3)
val t = (1, 2, 3)
I know I can create case class from tuple:
Foo.tupled(t)
but how can I create case class from Sequence? I have ~10 integer elements in the sequence.
case class Foo(a: Int, b: Int, c: Int)
val s = Seq(1, 2, 3)
val t = (1, 2, 3)
I know I can create case class from tuple:
Foo.tupled(t)
but how can I create case class from Sequence? I have ~10 integer elements in the sequence.
One option is to add corresponding apply
factory method to companion object something like so
object Foo {
def apply(xs: Seq[Int]): Option[Foo] = {
xs match {
case Seq(a, b, c) => Some(Foo(a, b, c))
case _ => None
}
}
}
Foo(s) // : Option[Foo] = Some(value = Foo(a = 1, b = 2, c = 3))
How aboud this?
case class Foo(xs: Int*)
val a = Foo(1,2,3)
val b = Foo(1,2,3,4,5)
val c = Foo((1 to 10).toList: _*)
println(a.xs) // Seq[Int](1,2,3)
println(c.xs) // Seq[Int] = List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)