Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to have tuple assignment to variables in Scala? [duplicate]

Possible Duplicate:
Tuple parameter declaration and assignment oddity

In Scala, one can do multiple-variable assignment to tuples via:

val (a, b) = (1, 2) 

But a similar syntax for assignment to variables doesn't appear to work. For example I'd like to do this:

var (c, d) = (3, 4) (c, d) = (5, 6) 

I'd like to reuse c and d in multiple-variable assignment. Is this possible?

like image 779
Heinrich Schmetterling Avatar asked Jun 01 '11 05:06

Heinrich Schmetterling


People also ask

How do you assign a tuple to two variables?

Summary. Python uses the commas ( , ) to define a tuple, not parentheses. Unpacking tuples means assigning individual elements of a tuple to multiple variables. Use the * operator to assign remaining elements of an unpacking assignment into a list and assign it to a variable.

Is tuple mutable in Scala?

In Scala, a tuple is a value that contains a fixed number of elements, each with its own type. Tuples are immutable.

Can Scala function return multiple values?

Function does not return multiple values but you can do this with the help of tuple.


1 Answers

This isn't simply "multiple variable assignment", it's fully-featured pattern matching!

So the following are all valid:

val (a, b) = (1, 2) val Array(a, b) = Array(1, 2) val h :: t = List(1, 2) val List(a, Some(b)) = List(1, Option(2)) 

This is the way that pattern matching works, it'll de-construct something into smaller parts, and bind those parts to new names. As specified, pattern matching won't bind to pre-existing references, you'd have to do this yourself.

var x: Int = _ var y: Int = _  val (a, b) = (1, 2) x = a y = b  // or  (1,2) match {   case (a,b) => x = a; y = b   case _ => } 
like image 89
Kevin Wright Avatar answered Oct 14 '22 18:10

Kevin Wright