Is it possible to have tuple assignment to variables in Scala?

23,713

Solution 1

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 _ =>
}

Solution 2

I don't think what you want is possible, but you can get something quite similar with the "magical" update method.

case class P(var x:Int, var y:Int) {
  def update(xy:(Int, Int)) {
    x = xy._1
    y = xy._2
  }
}

val p = P(1,2)
p() = (3,4)
Share:
23,713
Heinrich Schmetterling
Author by

Heinrich Schmetterling

Updated on July 09, 2022

Comments

  • Heinrich Schmetterling
    Heinrich Schmetterling almost 2 years

    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?

  • ziggystar
    ziggystar almost 13 years
    omg, am I supposed to understand this? Just to make a variable assignment?
  • ziggystar
    ziggystar almost 13 years
    And a case class with mutable members? Is this ok?
  • Kevin Wright
    Kevin Wright almost 13 years
    It's perfectly valid, even though it's a bit of a code smell
  • Kim Stebel
    Kim Stebel almost 13 years
    i agree it's a code smell, but I don't think there is a non-smelly way to answer this ;)