How are Scala closures transformed to Java objects?

Posted by iguana on Stack Overflow See other posts from Stack Overflow or by iguana
Published on 2010-04-19T19:49:51Z Indexed on 2010/04/19 19:53 UTC
Read the original article Hit count: 342

Filed under:
|
|

I'm currently looking at closure implementations in different languages. When it comes to Scala, however, I'm unable to find any documentation on how a closure is mapped to Java objects.

It is well documented that Scala functions are mapped to FunctionN objects. I assume that the reference to the free variable of the closure must be stored somewhere in that function object (as it is done in C++0x, e.g.).

I also tried compiling the following with scalac and then decompiling the class files with JD:

object ClosureExample extends Application { 
  def addN(n: Int) = (a: Int) => a + n
  var add5 = addN(5)
  println(add5(20))
}

In the decompiled sources, I see an anonymous subtype of Function1, which ought to be my closure. But the apply() method is empty, and the anonymous class has no fields (which could potentially store the closure variables). I suppose the decompiler didn't manage to get the interesting part out of the class files...

Now to the questions:

  • Do you know how the transformation is done exactly?
  • Do you know where it is documented?
  • Do you have another idea how I could solve the mystery?

© Stack Overflow or respective owner

Related posts about scala

Related posts about closures