Start learning free

LESSON 26 OF 348 · CALCULATIONS WITH NUMBERS

Augmented Assignment Operators in Kotlin: +=, -=, *=, /=, %=

Lesson Read the full explanation

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

    KOTLIN · CALCULATIONS WITH NUMBERS

    Augmented Assignment Operators in Kotlin, explained

    What augmented assignment is

    Changing a variable based on its own value is one of the most common things a program does. The long way to add 5 to a variable is to write the variable on both sides:

    myVar = myVar + 5
    

    Kotlin evaluates the right side first, using the current value of myVar, and then stores the result back into myVar. An augmented assignment does the same thing with less typing:

    var myVar = 10
    myVar += 5
    println(myVar)
    
    15
    

    Every arithmetic operator has one. Here they are with the equivalent long form:

    Short formLong formMeaning
    x += yx = x + yadd
    x -= yx = x - ysubtract
    x *= yx = x * ymultiply
    x /= yx = x / ydivide
    x %= yx = x % yremainder

    Kotlin details that matter here

    The variable must be a var

    An augmented assignment changes the variable, so the variable has to be declared with var. A val is read-only after it is initialized, and the compiler refuses to reassign it:

    fun main() {
        val n = 5
        n += 1
    }
    
    error: 'val' cannot be reassigned.
    

    Integer division drops the remainder

    When both operands are integers, / and /= do integer division. The fractional part is discarded, and the result is truncated toward zero:

    var x = 26
    x /= 5
    println(x) // 5
    
    var y = -7
    y /= 2
    println(y) // -3
    

    With a Double the division keeps the fraction: a variable holding 26.0 and divided by 5 becomes 5.2. The remainder operator %= follows the sign of the left operand, so -7 after %= 3 becomes -1.

    The type of the variable doesn't change

    A variable declared with var number = 18 is an Int for its whole life. Adding a Double to it with += doesn't turn it into a Double; the compiler reports a type mismatch instead:

    var n = 5
    n += 1.5
    
    error: assignment type mismatch: actual type is 'Double', but 'Int' was expected.
    

    Int overflow and division by zero

    An Int has 32 bits, and overflow wraps around silently. Adding 1 to Int.MAX_VALUE with += gives -2147483648. Use a Long when the numbers can get that large. Integer division by zero, such as n /= 0, throws an ArithmeticException with the message / by zero when the program runs.

    The right side can be any expression

    Kotlin computes the whole right-hand side before it combines the result with the variable. That makes x *= 2 + 3 mean x = x * (2 + 3), not x = x * 2 + 3. With x equal to 2, the result is 10. Other variables work too: with total at 10 and a val bonus = 4, the statement total += bonus * 2 leaves total at 18. The variable on the right can be a val, because only the variable on the left is changed.

    Other types

    The operators aren't only for numbers. += on a String variable appends text: after var s = "ab" and s += "cd", s holds "abcd". It creates a new string and stores it in the variable, because strings can't be modified.

    The lesson's exercise, step by step

    The exercise starts one variable and applies every operator to it in turn, so you can follow its value by hand:

    1. Create number with var, starting at 18. It has to be a var, because every later step reassigns it.
    2. Add 8 with +=. The value is now 26.
    3. Subtract 1 with --. This operator has no right-hand number: it always subtracts exactly one. The value is 25.
    4. Divide by 5 with /=. 25 divides evenly, so the value is 5.
    5. Add 1 with ++, the counterpart of --. The value is 6.
    6. Multiply by 3 with *=. The value is 18.
    7. Subtract 18 with -=. The value is back to 0.
    var number = 18
    number += 8
    number--
    number /= 5
    number++
    number *= 3
    number -= 18
    

    Note that number-- and number++ are used here as statements on their own lines. In that position, they are the same as number -= 1 and number += 1.

    Common mistakes

    • Using val. The code doesn't compile, as shown above.
    • Expecting a fraction from /= on an Int. 26 / 5 is 5, not 5.2.
    • Mixing up which side changes. The variable on the left is the one that changes. With a = 10 and b = 3, a -= b leaves a at 7, while b -= a leaves b at -7. Subtraction and division care about the order, so check which variable is on the left.
    • Putting a space inside the operator. + = is not an operator.

    Key takeaways

    • x op= y is shorthand for x = x op y, for +, -, *, / and %.
    • The variable must be a var, and it keeps its type.
    • Integer division truncates, and Int overflow wraps silently.
    • ++ and -- are shortcuts for adding or subtracting exactly one.
    Keep going with KotlinAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free