Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

scala

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 instead of the stack. I'm reading the Scala book of Martin Odersky but for now i didn't find this information. Can someone explain what's behind the hood?

like image 493
Sebastien Lorber Avatar asked Oct 11 '12 01:10

Sebastien Lorber


People also ask

What is the use of closures in Scala?

Scala Closures are functions which uses one or more free variables and the return value of this function is dependent of these variable. The free variables are defined outside of the Closure Function and is not included as a parameter of this function.

What is a free variable in Scala?

A free variable of an expression is a variable that's used inside the expression but not defined inside the expression. For instance, in the function literal expression (x: Int) => (x, y) , both variables x and y are used, but only y is a free variable, because it is not defined inside the expression.


1 Answers

An anonymous function (and actually, any function) in scala is actually an object (an instance of Function*). When it is instantiated, the capture of vals is done by copying the vals into internal fields of the function object. In the function body (that is, in the function object's apply method) the access to the captured vals is done by accessing these fields.

The capture of vars is similar, except that the compiler has to add a level of indirection: the var value is accessed through some hidden mutable holder (simply an object with a mutable field pointing to the current value of the var) and this is this holder that is copied into the function object. When writing into the var (either by local code or by the function object), it is the holder's field which is written. This mechanism ensures that the local code and function's code manipulate the same data, and both see each other's modifications.

So the answer is that a captured vals and a captured var both always live on the heap (whether directly as a field of the function object, or as a field of some wrapper object)

like image 51
Régis Jean-Gilles Avatar answered Nov 15 '22 05:11

Régis Jean-Gilles