Search code examples
kotlinintegeroperatorsvariable-assignmentincrement

Why are the "increment" and "decrement" operators not composable in Kotlin?


If I have a var i : Int = 0, then i.inc().inc() works just fine, i.e. inc() is composable with itself. Why then does (i++)++ make Kotlin report the error "Variable expected"?


Solution

  • The effect of computing the expression [a++] is:

    • Store the initial value of a to a temporary storage a0.

    • Assign the result of a0.inc() to a.

    • Return a0 as the result of the expression.

    So if you tried to use i++ as a above to determine the meaning of (i++)++, it would translate to

    val i1 = i++
    i++ = i1.inc()
    i1
    

    Of course, i++ = i1.inc() doesn't make sense (never mind that it would also calculate i++ twice).