1
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.

Dariusz Krynicki
  • 2,544
  • 1
  • 22
  • 47
  • Possible duplicate of https://stackoverflow.com/questions/17484384/packing-scala-tuple-to-custom-class-object – kosgeinsky Aug 26 '22 at 08:34
  • Of course it is not duplicate. I am asking about case class from sequence and not tuple. Read the question first before you flag it – Dariusz Krynicki Aug 26 '22 at 13:35

2 Answers2

6

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))
Mario Galic
  • 47,285
  • 6
  • 56
  • 98
0

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)

counter2015
  • 869
  • 7
  • 18