Junjie Wu
04/02/2022, 2:00 PM4
instead of 13
?
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 docJunjie Wu
04/02/2022, 2:01 PMfun 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
Joffrey
04/02/2022, 2:03 PMJunjie Wu
04/02/2022, 2:25 PManswer = answer + add(4, 5) { answer += it }
and
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?Joffrey
04/02/2022, 2:28 PM+
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 examplesJoffrey
04/02/2022, 2:31 PMJunjie Wu
04/02/2022, 2:35 PMJoffrey
04/02/2022, 2:46 PMThe 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-righthttps://kotlinlang.org/spec/expressions.html#function-calls-and-property-access
Junjie Wu
04/02/2022, 3:31 PMJunjie Wu
04/02/2022, 3:32 PM