Does any one have any idea why the following code ...
# getting-started
j
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
Your guess is correct, the doc about this is right there: https://kotlinlang.org/docs/operator-overloading.html#augmented-assignments
j
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
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
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
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
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