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 form | Long form | Meaning |
|---|---|---|
x += y | x = x + y | add |
x -= y | x = x - y | subtract |
x *= y | x = x * y | multiply |
x /= y | x = x / y | divide |
x %= y | x = x % y | remainder |
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:
- Create
numberwithvar, starting at 18. It has to be avar, because every later step reassigns it. - Add 8 with
+=. The value is now 26. - Subtract 1 with
--. This operator has no right-hand number: it always subtracts exactly one. The value is 25. - Divide by 5 with
/=. 25 divides evenly, so the value is 5. - Add 1 with
++, the counterpart of--. The value is 6. - Multiply by 3 with
*=. The value is 18. - 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 anInt.26 / 5is 5, not 5.2. - Mixing up which side changes. The variable on the left is the one that changes. With
a = 10andb = 3,a -= bleavesaat 7, whileb -= aleavesbat -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= yis shorthand forx = x op y, for+,-,*,/and%.- The variable must be a
var, and it keeps its type. - Integer division truncates, and
Intoverflow wraps silently. ++and--are shortcuts for adding or subtracting exactly one.