5

I have 3 variables that have already been initialized, and I want to assign a new value to all three of them. e.g.

var a = 1
var b = 2
var c = 3

and I want to reassign them to the same value e.g.

a = b = c = 4

But the above expression is invalid. Is there a right way to do this in Scala?

  • 9
    Two thoughts: a) Three separate assignment are not too terrible. b) Scala programmers avoid mutable variables, so this issue probably does not come up too much (and did not get special syntax). Maybe take a step back and see if you cannot replace the variables with `val`s. – Thilo Mar 15 '19 at 09:47
  • 3
    Somewhat related: https://stackoverflow.com/questions/9418576/assign-multiple-variables-at-once-in-scala – Thilo Mar 15 '19 at 09:49
  • 1
    Related: https://stackoverflow.com/questions/1998724/what-is-the-motivation-for-scala-assignment-evaluating-to-unit-rather-than-the-v – Brian McCutchon Mar 16 '19 at 16:15

2 Answers2

4

It is possible to slightly shorten the var definition code as follows

var (a, b, c) = (1, 2, 3)

This works because of extractor objects in scala. A tuple of 3 is extracted into 3 components it was created with.

But following does not work becase the extraction is applied on val or var definitions.

(a, b, c) = (4, 4, 4)
Ivan Stanislavciuc
  • 7,140
  • 15
  • 18
1

You can do this:

var Seq(a, b, c) = Seq.fill(3)(4)

As with Ivan's solution, this only works when declaring vars or vals, not when reassigning. Since the second parameter is computed for each element, it even works well for mutable objects:

import scala.collection.mutable.ListBuffer

var Seq(a, b, c) = Seq.fill(3)(ListBuffer[Int]())
a += 1  // Only modifies a, not b or c.

By contrast, something like a = b = c = [] will only create one list in most programming languages (e.g. Python, JavaScript, Java). If you don't want to create your object each time (perhaps because it is immutable and creation is expensive), declare it as val first to prevent this behavior:

val largeObject = ???
var Seq(a, b, c) = Seq.fill(3)(largeObject)
Brian McCutchon
  • 8,354
  • 3
  • 33
  • 45