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, used to subtract one from the value of a mutable variable. Under the hood, it acts as syntactic sugar for the dec() operator function, meaning the expression a-- or --a is translated by the compiler to a = a.dec(). The operator can be applied in two distinct positions relative to the operand, which dictates the evaluation order when used within a larger expression:
  1. Prefix (--a): The decrement operation is evaluated before the expression resolves. It subtracts one from the variable and returns the newly decremented value.
  2. Postfix (a--): The decrement operation is evaluated after the expression resolves. It returns the original value of the variable, and then subtracts one from the underlying variable in memory.
var x = 5
val y = --x // Prefix: x is decremented to 4, then y is assigned 4

var a = 5
val b = a-- // Postfix: b is assigned 5, then a is decremented to 4

Operator Overloading and Custom Types

Because Kotlin utilizes an operator overloading convention, the -- operator is not restricted to built-in numeric primitives. It can be applied to any custom class, provided the following conditions are met:
  1. The variable being decremented is mutable (declared as var), because the operator performs a reassignment.
  2. The type implements a dec() member function or extension function.
  3. The dec() function is prefixed with the operator keyword.
  4. The dec() function returns a value of the same type (or a subtype) as the caller.
class Counter(val value: Int) {
    // Defines the behavior for the '--' operator
    operator fun dec(): Counter {
        return Counter(value - 1)
    }
}

var myCounter = Counter(10)
myCounter-- // Compiler translates this to: myCounter = myCounter.dec()

Thread Safety

The -- operator is not atomic. The translation to a = a.dec() involves three distinct steps: reading the current value, invoking the decrement logic, and writing the new value back to the variable. In a multithreaded environment, concurrent use of the -- operator on shared variables requires explicit synchronization or the use of atomic classes (e.g., AtomicInteger.decrementAndGet()).
Master Kotlin with Deep Grasping Methodology!Learn More