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 the unary decrement operator. It decreases the value of its operand by one. At compile time, Kotlin translates the -- operator into a call to the dec() operator function, followed by a reassignment to the original operand. The operator operates in two distinct evaluation modes depending on its position relative to the operand: Prefix Decrement (--a) The operand is decremented first, and the expression evaluates to the new decremented value. Postfix Decrement (a--) The expression evaluates to the original value of the operand, and the operand is decremented immediately afterward.
var prefixVar = 10
val prefixResult = --prefixVar 
// prefixVar is now 9
// prefixResult is 9

var postfixVar = 10
val postfixResult = postfixVar-- 
// postfixVar is now 9
// postfixResult is 10

Compiler Translation

Because Kotlin supports operator overloading, the -- operator is not limited to primitive numeric types. When the compiler encounters --a or a--, it resolves the operation to specific underlying execution steps to preserve the correct evaluation state. Prefix Translation (--a)
a = a.dec()
// The expression evaluates to the new value of 'a'
Postfix Translation (a--)
val a0 = a       // Cache the original value
a = a0.dec()     // Reassign the decremented value
// The expression evaluates to 'a0'

Operator Overloading for Custom Types

To enable the -- operator on a custom class, you must define an operator fun dec() that returns a value of the same type (or a subtype). The compiler automatically handles the reassignment of the returned value back to the operand.
class Vector(val x: Int, val y: Int) {
    // The dec() function must be marked with the 'operator' modifier
    operator fun dec(): Vector {
        return Vector(x - 1, y - 1)
    }
}

var v = Vector(5, 5)
v-- 
Technical Constraints:
  • The operand must be an expression that is valid on the left-hand side of an assignment. This includes mutable local variables (var), mutable properties of objects (obj.property--), and indexed access expressions where the get operator returns a non-nullable type (e.g., array[0]--).
  • The dec() function must return a value. It should not mutate the object in place and return Unit, as the compiler explicitly reassigns the result of dec() to the original operand reference.
  • Nullable types do not possess a dec() operator. Consequently, applying -- to an indexed access expression that returns a nullable type (such as map[key]-- on a standard MutableMap) will result in a compilation error.
Master Kotlin with Deep Grasping Methodology!Learn More