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

前端 未结 2 1977
深忆病人
深忆病人 2020-12-13 06:03

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().

相关标签:
2条回答
  • 2020-12-13 06:43

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

    0 讨论(0)
  • 2020-12-13 06:50

    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 讨论(0)
提交回复
热议问题