https://kotlinlang.org logo
#getting-started
Title
# getting-started
j

Junjie Wu

04/02/2022, 2:00 PM
Does any one have any idea why the following code prints
4
instead of
13
?
Copy code
fun add(a: Int, b: Int, cumulate: (Int) -> Unit): Int {
    cumulate(a + b)
    return a
}

fun main() {
    var answer = 0
    answer += add(4, 5) { answer += it }
    println(answer)
}
my guess is that
answer += x
equals to
answer = answer + x
where the second answer equals to 0, but I can’t find any prove on doc
Copy code
fun add(a: Int, b: Int, cumulate: (Int) -> Unit): Int {
    cumulate(a + b)
    return a
}

fun main() {
    var answer = 0
    val temp = add(4, 5) { answer += it }
    answer += temp
    println(answer)
}
will print
13
j

Joffrey

04/02/2022, 2:03 PM
Your guess is correct, the doc about this is right there: https://kotlinlang.org/docs/operator-overloading.html#augmented-assignments
j

Junjie Wu

04/02/2022, 2:25 PM
it seems
Copy code
answer = answer + add(4, 5) { answer += it }
and
Copy code
answer = add(4, 5) { answer += it } + answer
yields different result. this could be due to evaluation order in the expression, wonder does Kotlin compiler guarantee any order in such case?
j

Joffrey

04/02/2022, 2:28 PM
Yes the left operand of
+
is evaluated first. I don't have the spec links but I'm 99% sure the evaluation order of expressions is indeed guaranteed - respecting parentheses, operator precedence, and left-to-right otherwise. This explains the difference in your last 2 examples
👍 1
Here you go for the operator precedence reference: https://kotlinlang.org/docs/reference/grammar.html#expressions
j

Junjie Wu

04/02/2022, 2:35 PM
It makes sense that the order is guaranteed. I was thinking that function parameter evaluation order is not guaranteed so get a little suspecious about the expression order.
j

Joffrey

04/02/2022, 2:46 PM
What do you mean by the function parameter evaluation not being guaranteed?
The evaluation of a function call begins with the evaluation of its explicit receiver, if it is present. Function arguments are then evaluated in the order of their appearance in the function call left-to-right
https://kotlinlang.org/spec/expressions.html#function-calls-and-property-access
j

Junjie Wu

04/02/2022, 3:31 PM
wow, awesome
I’m more familiar with cpp, and it’s function parameter evaluation order it not guaranteed…. so I presume Kotlin is the same way, huge thanks for correcting me!
👍 1
2 Views