为什么 `variable++` 会增加变量而 `variable + 1` 不会?

Cac*_*ide 0 kotlin

这是我遇到此问题的问题:

该函数应该比较每个索引位置的值,如果该位置的值更高,则得分。如果它们相同,则没有意义。给定的a = [1, 1, 1] b = [1, 0, 0]输出应该是[2, 0]

fun compareArrays(a: Array<Int>, b: Array<Int>): Array<Int> {

    var aRetVal:Int = 0
    var bRetVal:Int = 0

    for(i in 0..2){
        when {
            a[i] > b[i] -> aRetVal + 1 // This does not add 1 to the variable
            b[i] > a[i] -> bRetVal++ // This does...
        }
    }
    return arrayOf(aRetVal, bRetVal)

}
Run Code Online (Sandbox Code Playgroud)

IDE 甚至说 aRetVal 是未修改的,应该声明为 val

use*_*612 5

What others said is true, but in Kotlin there's more. ++ is just syntactic sugar and under the hood it will call inc() on that variable. The same applies to --, which causes dec() to be invoked (see documentation). In other words a++ is equivalent to a.inc() (for Int or other primitive types that gets optimised by the compiler and increment happens without any method call) followed by a reassignment of a to the incremented value.

As a bonus, consider the following code:

fun main() {
    var i = 0
    val x = when {
        i < 5 -> i++
        else -> -1
    }

    println(x) // prints 0
    println(i) // prints 1

    val y = when {
        i < 5 -> ++i
        else -> -1
    }

    println(y) // prints 2
    println(i) // prints 2 
}
Run Code Online (Sandbox Code Playgroud)

The explanation for that comes from the documentation I linked above:

The compiler performs the following steps for resolution of an operator in the postfix form, e.g. a++:

  • Store the initial value of a to a temporary storage a0;
  • 将 a.inc() 的结果赋值给 a;
  • 返回 a0 作为表达式的结果。

...

对于前缀形式++a--a解析的工作方式相同,效果是:

  • 将 a.inc() 的结果赋值给 a;
  • 作为表达式的结果返回 a 的新值。