With Scala closures, when do captured variables start to live on the JVM heap?

后端 未结 2 1978
抹茶落季
抹茶落季 2021-01-13 06:55

Related question: Scala closures compared to Java innerclasses -> final VS var

I wonder when do Scala makes the variables captured into a closure live on the heap

2条回答
  •  暗喜
    暗喜 (楼主)
    2021-01-13 07:36

    I don't know the insides of the compiler, but here is how it can be done. For each local variable, the compiler maintains a flag initialized to false. Whenever the variable is used, the compiler checks whether it is being used inside a class or closure that doesn't contain the variable's declaration; if so the flag is set to true. At the end of the variable's scope, if the flag is still false, the variable can live on the stack. Otherwise it must live on the heap.

提交回复
热议问题