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?
FWIW, I wanted a tuple to initalise a number of fields and wanted to use the syntactic sugar of tuple assignment. EG:
It turns out that there is syntactic sugar for assigning the contents of a list too...
So no need for tuples if you've got the same problem.
This can also be done in
shapeless
with less boilerplate usingSized
:It's type-safe: you get
None
, if the tuple size is incorrect, but the tuple size must be a literal orfinal val
(to be convertible toshapeless.Nat
).as far as you have the type:
You can't do this in a typesafe way. Why? Because in general we can't know the length of a list until runtime. But the "length" of a tuple must be encoded in its type, and hence known at compile time. For example,
(1,'a',true)
has the type(Int, Char, Boolean)
, which is sugar forTuple3[Int, Char, Boolean]
. The reason tuples have this restriction is that they need to be able to handle a non-homogeneous types.If you are very sure that your list.size<23 use it:
Shapeless 2.0 changed some syntax. Here's the updated solution using shapeless.
The main issue being that the type for .toHList has to be specified ahead of time. More generally, since tuples are limited in their arity, the design of your software might be better served by a different solution.
Still, if you are creating a list statically, consider a solution like this one, also using shapeless. Here, we create an HList directly and the type is available at compile time. Remember that an HList has features from both List and Tuple types. i.e. it can have elements with different types like a Tuple and can be mapped over among other operations like standard collections. HLists take a little while to get used to though so tread slowly if you are new.