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?
You can convert a list into a tuple simply by passing to the tuple function.
Lists are mutable(values can be changed) whereas tuples are immutable(values cannot be changed).
In Scala, a tuple is a value that contains a fixed number of elements, each with its own type. Tuples are immutable. Tuples are especially handy for returning multiple values from a method. This creates a tuple containing a String element and an Int element.
You can do it using scala extractors and pattern matching (link):
val x = List(1, 2, 3) val t = x match { case List(a, b, c) => (a, b, c) }
Which returns a tuple
t: (Int, Int, Int) = (1,2,3)
Also, you can use a wildcard operator if not sure about a size of the List
val t = x match { case List(a, b, c, _*) => (a, b, c) }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With