TheDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
++ 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:
- Evaluate the receiver
aonce and store its current value in a temporary variable (temp = a). - Call
inc()on the temporary variable and assign the result back toa(a = temp.inc()). - Return the new value of
a.
- Evaluate the receiver
a++)
The postfix form returns the original value of the expression before the increment occurs.
- Resolution:
- Evaluate the receiver
aonce and store its current value in a temporary variable (temp = a). - Call
inc()on the temporary variable and assign the result back toa(a = temp.inc()). - Return the original cached value (
temp).
- Evaluate the receiver
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.
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]++orlist[i]++), even if the array or list reference itself is declared as a read-onlyval. - Type Compatibility: The return type of the
inc()function must be the same type as the original expression, or a subtype, to satisfy the implicita = temp.inc()reassignment step.
Master Kotlin with Deep Grasping Methodology!Learn More





