Search code examples
scalatuplesiterable-unpacking

Is there way to create tuple from list(without codegeneration)?


Sometimes there are needs to create tuples from small collections(for example scalding framework).

def toTuple(list:List[Any]):scala.Product = ...

Solution

  • If you don't know the arity up front and want to do a terrible terrible hack, you can do this:

    def toTuple[A <: Object](as:List[A]):Product = {
      val tupleClass = Class.forName("scala.Tuple" + as.size)
      tupleClass.getConstructors.apply(0).newInstance(as:_*).asInstanceOf[Product]
    }
    toTuple: [A <: java.lang.Object](as: List[A])Product
    
    scala> toTuple(List("hello", "world"))
    res15: Product = (hello,world)