Skip to main content
The ++ (increment) operator is a unary operator that increases the value of a mutable variable. In Kotlin, it is not a primitive-only operation but rather syntactic sugar for the inc() operator function combined with a reassignment. Because Kotlin treats the increment operation as a reassignment, the operand must be declared as a mutable variable (var), not a read-only reference (val).

Evaluation Modes

The operator exhibits different evaluation semantics based on its position relative to the operand:
  • Prefix (++a): The variable is incremented first, and the expression evaluates to the new (incremented) value.
  • Postfix (a++): The expression evaluates to the original value of the variable, and the variable is incremented afterward.

Compiler Translation

Under the hood, Kotlin translates the ++ operator into a call to the inc() function followed by an assignment back to the original variable. Prefix Translation:
Postfix Translation: To preserve the original value for the expression while ensuring the getter of a is evaluated exactly once, the compiler uses a temporary reference.

Operator Overloading and Mutability Contract

Because ++ is resolved via operator overloading, it can be applied to any custom class by defining an inc() member or extension function prefixed with the operator keyword. The function must return a type that is assignable to the original variable. Crucially, the inc() function must never mutate the existing object; it must always return a new instance. If inc() mutates the internal state and returns this, the postfix operator will violate its semantic contract. In the postfix translation (val a0 = a; a = a0.inc(); val b = a0), if a0.inc() mutates a0, the temporary variable a0 will reflect the mutated state, causing the postfix expression to incorrectly evaluate to the new value instead of the original.

Thread Safety

The ++ operator in Kotlin is not atomic. Whether applied to primitives or custom objects, the read-modify-write cycle (a = a.inc()) is subject to race conditions in a multithreaded environment. For atomic increments, Kotlin relies on the underlying platform’s concurrency utilities (e.g., AtomicInteger.incrementAndGet() on the JVM), which bypass the ++ operator syntax entirely.
Tired of Poor Kotlin Skills? Fix That With Deep Grasping!Learn More