CodeBlanks Logo Icon CodeBlanks

Assignment operators

Learn shortcut assignments with =, +=, -=, *=, /= and ++/--.

Assignment operators

The = operator assigns a value to a variable. Kotlin also offers compound assignment operators: +=, -=, *=, /=, %=. These perform the operation and the assignment in a single step.

For example, x += 5 is the same as x = x + 5. You can also increment or decrement a variable by one with ++ and --.

var x = 10
x += 5      // x = 15
x -= 3      // x = 12
x++         // x = 13
x--         // x = 12

Practice Try compound assignment

Write a fun main(). Declare var total = 10. Increment with total += 5 and print with println(total).

Sample solution

Main.kt
fun main() {
    var total = 10
    total += 5
    println(total)
}

Expected output

15

Prefix and postfix ++ and --

The ++ and -- operators can come before or after the variable. ++x increments first then yields the value; x++ yields the value first then increments.

Standalone, both yield the same result. But inside an expression, they differ. So to avoid confusion, prefer standalone use.

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Assignment operators: fill in the missing part

Question
var x = 10
x ____= 5  // x = 15
Answer
var x = 10
x += 5  // x = 15

Explanation: The compound add-assign operator is +=.

2 What does `x += 5` do?

  • Adds 5 to x Correct answer
  • Sets x to 5
  • Multiplies x by 5
  • It throws an error

Explanation: The += operator adds 5 to x.

3 Assignment operators: match the terms

Term Meaning
= Assign
+= Add and assign
-= Subtract and assign
++ Increment

All lessons in Beginner