Convert Vector to Tuple scala

2.2k views Asked by At

Is it possible to convert a vector of heterogeneous vectors to list of Tuple3 in Scala

i.e.

Vector(Vector(1,"a","b"),Vector(2,"b","c")) to List(Tuple3(1,"a","b"),Tuple3(2,"b","c"))
1

There are 1 answers

11
Sergii Lagutin On BEST ANSWER

Explicitly convert every inner Vector to Tuple3:

vector.map {
    case Vector(f, s, t) => Tuple3(f, s, t)
}.toList

If you have vectors of variadic size you can use more general approach:

def toTuple(seq: Seq[_]): Product = {
  val clz = Class.forName("scala.Tuple" + seq.size)
  clz.getConstructors()(0).newInstance(seq.map(_.asInstanceOf[AnyRef]): _*).asInstanceOf[Product]
}

vector.map(toTuple).toList

But it has restriction: max length of vectors is 22.