How can I convert a list with (say) 3 elements into a tuple of size 3?
For example, let's say I have val x = List(1, 2, 3)
and I want to convert this into (1, 2, 3)
. How can I do this?
How can I convert a list with (say) 3 elements into a tuple of size 3?
For example, let's say I have val x = List(1, 2, 3)
and I want to convert this into (1, 2, 3)
. How can I do this?
2015 post. For the Tom Crockett's answer to be more clarifying, here is a real example.
At first, I got confused about it. Because I come from Python, where you can just do
tuple(list(1,2,3))
.Is it short of Scala language ? (the answer is -- it's not about Scala or Python, it's about static-type and dynamic-type.)
That's causes me trying to find the crux why Scala can't do this .
The following code example implements a
toTuple
method, which has type-safetoTupleN
and type-unsafetoTuple
.The
toTuple
method get the type-length information at run-time, i.e no type-length information at compile-time, so the return type isProduct
which is very like the Python'stuple
indeed (no type at each position, and no length of types).That way is proned to runtime error like type-mismatch or
IndexOutOfBoundException
. (so Python's convenient list-to-tuple is not free lunch. )Contrarily , it is the length information user provided that makes
toTupleN
compile-time safe.Despite the simplicity and being not for lists of any length, it is type-safe and the answer in most cases:
Another possibility, when you don't want to name the list nor to repeat it (I hope someone can show a way to avoid the Seq/head parts):
an example using shapeless :
Note: the compiler need some type informations to convert the List in the HList that the reason why you need to pass type informations to the
toHList
methodYou can't do this in a type-safe way. In Scala, lists are arbitrary-length sequences of elements of some type. As far as the type system knows,
x
could be a list of arbitrary length.In contrast, the arity of a tuple must be known at compile time. It would violate the safety guarantees of the type system to allow assigning
x
to a tuple type.In fact, for technical reasons, Scala tuples were limited to 22 elements, but the limit no longer exists in 2.11 The case class limit has been lifted in 2.11 https://github.com/scala/scala/pull/2305
It would be possible to manually code a function that converts lists of up to 22 elements, and throws an exception for larger lists. Scala's template support, an upcoming feature, would make this more concise. But this would be an ugly hack.
you can do this either
by iterating through the list and applying each element one by one.
You can do it using scala extractors and pattern matching (link):
Which returns a tuple
Also, you can use a wildcard operator if not sure about a size of the List