Back to questions
JuniorTheoryCommon
What does the program print?
fun main() {
var count = 0
val tick = { count += 1 }
tick()
tick()
println(count)
}2
- Expecting
0: a lambda does not get a copy ofcount. It remembers the variable itself, so both calls change thecountthatprintlnreads. - Expecting the body to run when the lambda is created:
val tick = { count += 1 }only stores it, socountgrows only on the twotick()calls.
- What does the program print if you add
count = 10between the two calls? - What changes if
countis declared withvalinstead ofvar?