Start learning free

LESSON 27 OF 348 · CALCULATIONS WITH NUMBERS

Increment & Decrement Operators in Scala in Scala

Lesson

In programming, increasing the value of a variable by 1 is so common, there is an operator designed to do that.

That operator is the increment operator (+= 1):

var number: Int = 10
number += 1 // short for number = number + 1

println(number) // Output: 11

There is also one such operator for decreasing the value of a variable by 1.

That operator is the decrement operator (-= 1):

var number: Int = 10
number -= 1 // short for number = number - 1

println(number) // Output: 9

Postfix:

In the examples above, we have used these two operators in their postfix form, with operator (+= 1) after operand (number) such as number += 1.

If used postfix, the increment operator increments and returns the value before incrementing:

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). It's equivalent to this:

val oldNumber = number
number += 1

Prefix:

However, there is also the prefix form, with operator before operand (for example, number += 1).

When used prefix, the increment operator increments and returns the value after incrementing:

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 oldNumber (making it 11). It's equivalent to this:

number += 1
val newNumber = number

Here's an example with the decrement operator:

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.


STEP 1 OF 5
    Ctrl + Enter to check

    Increment And Decrement 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