有没有办法从列表创建元组(没有代码生成)? [英] Is there way to create tuple from list(without codegeneration)?

查看:24
本文介绍了有没有办法从列表创建元组(没有代码生成)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

推荐答案

如果你事先不知道 arity 并且想做一个可怕的骇客,你可以这样做:

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)

这篇关于有没有办法从列表创建元组(没有代码生成)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆