我想知道这段代码的结果
object localTest {
def hello = {
var t = 3
() => {
t = t + 3
println(t)
}
}
}
object mainObj {
def main(args: Array[String]): Unit = {
val test = localTest.hello
while (true) {
Thread.sleep(1000)
test()
}
}
}
为什么函数中的变量t
只hello
赋值一次,结果是6,9,12....
我猜这可能与闭包属性有关,但为什么var t = 3
只执行一次?