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.
views:
199answers:
1
+7
A:
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).
Mitch Blevins
2009-12-17 02:10:29
Looks good, though you need `myTuple.productArity - 1` and `productElement()` returns an `Any`. Is there any way to maintain the inner type information.
pr1001
2009-12-17 02:40:46
Corrected indexing off-by-one and added type maintaining comment in answer.
Mitch Blevins
2009-12-17 03:39:22
Thanks, looks good.
pr1001
2009-12-17 08:56:37
productElements is deprecated, use myTuple.productIterator.toList instead
tommy chheng
2010-03-29 05:05:06
Answer edited to reflect latest version per Tommy Chheng's comment.
Mitch Blevins
2010-03-29 11:35:56