Is there way to create tuple from list(without codegeneration)?

后端 未结 6 2202
[愿得一人]
[愿得一人] 2020-11-27 17:44

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

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

6条回答
  •  Happy的楠姐
    2020-11-27 18:26

    You really don't want your method to return Product since this is uselessly vague. If you want to be able to use the returned object as a tuple, then you'll have to know its arity. So what you can do is have a series of toTupleN methods for different arities. For convenience, you can add these as implicit methods on Seq.

    How about this:

    class EnrichedWithToTuple[A](elements: Seq[A]) {
      def toTuple2 = elements match { case Seq(a, b) => (a, b) }
      def toTuple3 = elements match { case Seq(a, b, c) => (a, b, c) }
      def toTuple4 = elements match { case Seq(a, b, c, d) => (a, b, c, d) }
      def toTuple5 = elements match { case Seq(a, b, c, d, e) => (a, b, c, d, e) }
    }
    implicit def enrichWithToTuple[A](elements: Seq[A]) = new EnrichedWithToTuple(elements)
    

    and use it like:

    scala> List(1,2,3).toTuple3
    res0: (Int, Int, Int) = (1,2,3)
    

提交回复
热议问题