Search code examples
listscalatuples

Convert a Scala list to a tuple?


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?


Solution

  • 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 for Tuple3[Int, Char, Boolean]. The reason tuples have this restriction is that they need to be able to handle a non-homogeneous types.