有没有办法从列表中创建元组(没有代码生成)?

有没有办法从列表中创建元组(没有代码生成)?

问题描述:

有时需要从小的集合中创建元组(例如 scalding 框架).

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

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

如果你不知道前面的 arity 并且想要做一个可怕的 hack,你可以这样做:

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)