scalascala-collectionsscala-2.10scalaz7

Convert Vector to Tuple scala


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"))

Solution

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