44

我有一个Tuple2ofList[List[String]]并且我希望能够将元组转换为一个列表,以便我可以使用List.transpose(). 有没有办法做到这一点?另外,我知道它是一个Pair,尽管我一直是通用解决方案的粉丝。

4

2 回答 2

83

适用于任何元组(scala 2.8):

myTuple.productIterator.toList

斯卡拉 2.7:

(0 to (myTuple.productArity-1)).map(myTuple.productElement(_)).toList

不确定如何维护一般产品或元组的类型信息,但对于 Tuple2:

def tuple2ToList[T](t: (T,T)): List[T] = List(t._1, t._2)

当然,您可以为所有元组(最多 22 个)定义类似的类型安全转换。

于 2009-12-17T02:10:29.907 回答
10

使用无形 -

@ import syntax.std.tuple._
import syntax.std.tuple._
@ (1,2,3).toList
res21: List[Int] = List(1, 2, 3)
@ (1,2,3,4,3,3,3,3,3,3,3).toList
res22: List[Int] = List(1, 2, 3, 4, 3, 3, 3, 3, 3, 3, 3)

请注意,使用 Shapeless 不会丢失类型信息toList

于 2017-05-01T07:54:48.083 回答