Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a Scala list to a tuple?

Tags:

list

tuples

scala

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?

like image 770
grautur Avatar asked Feb 06 '13 06:02

grautur


People also ask

Can you convert a list to a tuple?

You can convert a list into a tuple simply by passing to the tuple function.

What is the difference between list and tuple in Scala?

Lists are mutable(values can be changed) whereas tuples are immutable(values cannot be changed).

Does Scala have tuples?

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.


Video Answer


1 Answers

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) } 
like image 84
kikulikov Avatar answered Oct 02 '22 11:10

kikulikov