Start learning free

LESSON 26 OF 348 · CALCULATIONS WITH NUMBERS

Augmented Assignment Operators in Scala in Scala

Lesson

In programming, it is common to use assignments to modify the contents of a variable.

Remember that everything to the right of the equals sign (=) is evaluated first, so we can say:

myVar = myVar + 5

to add 5 to myVar.

Since this is such a common pattern, there are operators which do both a mathematical operation and assignment in one step.

One such operator is the += operator:

var myVar = 10
myVar += 5
println(myVar) // Output: 15

This code would print 15 to the console. We call myVar += 5 an augmented assignment.

There is one such operator for every other arithmetic operator we've learned:

For subtraction: -=

var myVar = 10
myVar -= 5 // short for myVar = myVar - 5
println(myVar) // Output: 5

For multiplication: *=

var myVar = 3
myVar *= 5 // short for myVar = myVar * 5
println(myVar) // Output: 15

For division: /=

var myVar = 20
myVar /= 4 // short for myVar = myVar / 4
println(myVar) // Output: 5

For remainder: %=

var myVar = 11
myVar %= 3 // short for myVar = myVar % 3
println(myVar) // Output: 2

Assignment
Follow the Coding Tutorial and let's do some augmented assignments.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 7
    Ctrl + Enter to check

    Augmented Assignment Operators in Scala

    Keep going with ScalaAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free