🎓 A1Learner
🔍
0 of 50 lessons completed

Scala Assignment Operators

Assignment operators are shortcuts that update a var in place. They do the math and store the new value back in the same var.

+= adds and stores

The var score starts at 10. Each += line adds to the stored value, so the total keeps growing.

@main def main(): Unit =
  var score = 10
  score += 5
  println(score)
  score += 3
  println(score)

-=, *= and /= update in steps

Each shortcut changes the stored value before the next line runs. Printing after each step shows the value move.

@main def main(): Unit =
  var x = 20
  x -= 5
  println(x)
  x *= 2
  println(x)
  x /= 3
  println(x)

x += 1 adds one

Scala has no ++ sign for adding one. Writing x += 1 does the same job.

@main def main(): Unit =
  var count = 5
  count += 1
  println(count)
  count += 1
  println(count)

Example

@main def main(): Unit =
  var balance = 100
  balance += 50
  println(balance)
  balance -= 30
  println(balance)
  balance *= 2
  println(balance)
  balance /= 4
  println(balance)

Key points

  • Add and assign: x += 5 adds 5 to x and stores the result in x.
  • Subtract and assign: x -= 2 takes 2 away from x and stores the result in x.
  • Multiply and assign: x *= 3 multiplies x by 3 and stores the result in x.
  • Divide and assign: x /= 2 divides x by 2 and stores the result in x.
  • Var only: these shortcuts change a value, so they work on a var and not on a val.

In this example, balance starts at 100 and grows to 150 after += 50. It drops to 120 after -= 30, then doubles to 240 with *= 2. Dividing by 4 with /= 4 leaves 60.

Note

Scala has no ++ sign, so x += 1 is the way to add one.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Scastie

Exercise

What does this code print? var x = 10, then x *= 3, then println(x).