开发者

Are there any methods included in Scala to convert tuples to lists?

开发者 https://www.devze.com 2022-12-14 01:27 出处:网络
I have a Tuple2 of List[List[String]] and I\'d like to be able to convert the tuple to a list so that I can then use List.transpose(). Is there any way to do this? Also, I know it\'s a Pair, though I\

I have a Tuple2 of List[List[String]] and I'd like to be able to convert the tuple to a list so that I can then use List.transpose(). Is there any way to do this? Also, I know it's a Pair, though I'm always a fan of 开发者_运维知识库generic solutions.


Works with any tuple (scala 2.8):

myTuple.productIterator.toList

Scala 2.7:

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

Not sure how to maintain type info for a general Product or Tuple, but for Tuple2:

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

You could, of course, define similar type-safe conversions for all the Tuples (up to 22).


Using Shapeless -

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

Note that type information is not lost using Shapeless's toList.

0

精彩评论

暂无评论...
验证码 换一张
取 消