How are closures implemented in scala?

前端 未结 3 413
日久生厌
日久生厌 2020-12-21 02:22

How are the variables outside of the scope of the function pulled into the function when it\'s created? I tried decompiling, but I had trouble understanding it. It looked

3条回答
  •  感情败类
    2020-12-21 03:05

    Here is the Bytecode for the following method containing a closure:

    def run()
    {
    val buff = new ArrayBuffer[Int]();
    
    val i = 7;
    
    buff.foreach( a =>  {  a + i  }  )
    }
    

    Bytecode:

      public class com.anarsoft.plugin.scala.views.ClosureTest$$anonfun$run$1 extends   scala.runtime.AbstractFunction1$mcII$sp implements scala.Serializable {
    
    // Field descriptor #14 J
    public static final long serialVersionUID = 0L;
    
    // Field descriptor #18 I
    private final int i$1;
    
    public ClosureTest$$anonfun$run$1(com.anarsoft.plugin.scala.views.ClosureTest $outer, int i$1);
    
    ...
    

    The Compiler generates a new ClosureTest$$anonfun$run$1 with a constructor with two fields for the variables outside the scope, e.g. i and this of the calling class.

提交回复
热议问题