Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

The ++ operator in Kotlin is a unary arithmetic operator used to increment the value of an assignable expression. Under the hood, it acts as syntactic sugar for the inc() operator function. Kotlin guarantees strict single-evaluation for the receiver, meaning the expression being incremented is evaluated exactly once, even if it involves custom getters or indexed access.

Evaluation Strategies

The operator has two distinct syntactic forms that dictate the order of evaluation and the returned value. To prevent evaluating the receiver multiple times, the compiler utilizes temporary variables during resolution. 1. Prefix (++a) The prefix form increments the expression and returns the newly incremented value.
  • Resolution:
    1. Evaluate the receiver a once and store its current value in a temporary variable (temp = a).
    2. Call inc() on the temporary variable and assign the result back to a (a = temp.inc()).
    3. Return the new value of a.
var a = 5
val b = ++a // a becomes 6, b is assigned 6
2. Postfix (a++) The postfix form returns the original value of the expression before the increment occurs.
  • Resolution:
    1. Evaluate the receiver a once and store its current value in a temporary variable (temp = a).
    2. Call inc() on the temporary variable and assign the result back to a (a = temp.inc()).
    3. Return the original cached value (temp).
var x = 5
val y = x++ // y is assigned 5, x becomes 6

Operator Overloading

To utilize the ++ operator with custom types, the class must define an inc() method prefixed with the operator modifier. Because the ++ operator inherently performs a reassignment, the inc() function must return a new instance (or the mutated instance) that is assignable back to the original expression.
class Counter(val value: Int) {
    operator fun inc(): Counter {
        return Counter(value + 1)
    }
}

var myCounter = Counter(10)
myCounter++ // Resolves using the single-evaluation strategy: temp = myCounter; myCounter = temp.inc()

Compiler Requirements

  • Assignable Expression: The operand must be an assignable expression. While this includes mutable variables (var), it also encompasses mutable properties and indexed access expressions (e.g., array[0]++ or list[i]++), even if the array or list reference itself is declared as a read-only val.
  • Type Compatibility: The return type of the inc() function must be the same type as the original expression, or a subtype, to satisfy the implicit a = temp.inc() reassignment step.
Master Kotlin with Deep Grasping Methodology!Learn More