In programming, increasing the value of a variable by 1 is so common that many languages have an operator designed to do that (++).
Scala has no ++ operator. Instead, we increment a var with the augmented assignment += 1:
var number: Int = 10
number += 1 // short for number = number + 1
println(number) // Output: 11
Scala has no -- operator either. We decrement a variable, that is decrease its value by 1, with -= 1:
var number: Int = 10
number -= 1 // short for number = number - 1
println(number) // Output: 9
Postfix:
In languages that have ++, it comes in two forms. In the postfix form, the operator comes after the operand (number++) and gives the value before incrementing.
In Scala, number += 1 doesn't give a value, but we can get the same effect by saving the old value before we increment:
var number: Int = 10
val oldNumber = number
number += 1
println(oldNumber) // Output: 10
println(number) // Output: 11
This code first assigns the value of number (which is 10) to oldNumber and then increments number (making it 11).
Prefix:
The other form is the prefix form, with the operator before the operand (++number), which gives the value after incrementing.
In Scala, we get the same effect by incrementing first and reading the value afterwards:
var number: Int = 10
number += 1
val newNumber = number
println(newNumber) // Output: 11
println(number) // Output: 11
This code first increments number (making it 11) and then assigns the new value of number to newNumber (making it 11).
Here's an example with decrementing:
var number: Int = 10
number -= 1
val newNumber = number
println(newNumber) // Output: 9
println(number) // Output: 9
Assignment
Follow the Coding Tutorial and let's practice with these operators!
Hint
Look at the examples above if you get stuck.
Free plan: 30 tutor messages. PRO is unlimited.
