Scala编译:匿名函数 [英] Scala compilation: anonymized function

查看:140
本文介绍了Scala编译:匿名函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么规格的scala编译器可以解释这种行为吗?

Is there any specification of scala compilator that can explain that behaviour?

scala版本:2_10_6

scala version: 2_10_6

代码示例

trait Service {
  def process(s: String)
}

object ServiceImpl extends Service{
  override def process(s: String): Unit = {
    println(s)
  }
}

object Register {
  var serviceInst : Service = ServiceImpl
}

object Client1 {    
  def process1(l: List[String]): Unit ={
    l.foreach(x => Register.serviceInst.process(x))
  }      
}

object Client2 {    
  def process1(l: List[String]): Unit ={
    l.foreach(Register.serviceInst.process)
  }      
}






我假设process1和process2应该有类似的行为。但是,在comilation / decom之后


I assume that process1 and process2 should have the similar behaviour. However, after comilation / decom

public final class Client1$$anonfun$process$1$$anonfun$apply$1 extends AbstractFunction1<String, BoxedUnit> implements Serializable {
    public static final long serialVersionUID = 0L;
    public final void apply(final String x$1) {
        Register$.MODULE$.serviceInst().process(x$1);
    }
}

public static final class Client2$$anonfun$process$1 extends AbstractFunction1<String, BoxedUnit> implements Serializable {
    public static final long serialVersionUID = 0L;
    private final Service eta$0$1$1;

    public final void apply(final String s) {
        this.eta$0$1$1.process(s);
    }
}


推荐答案

因为Scala编译器对 Client2 中给出的方法执行eta-expansion,它通过生成调用<$ c $的 Function 直接在具体的服务实例上执行 c

It's because Scala compiler performs eta-expansion on method given in Client2, which works by generating Function that calls process directly on a concrete Service instance.

这些函数看起来像之前它们变成字节码:

Here is an example how these functions look like before they are turned into bytecode:

object Client1 {    
  def process1(l: List[String]): Unit = {
    l.foreach(new Function1[String, Unit] {
      def apply(x: String) = Register.serviceInst.process(x)
    })
  }      
}

object Client2 {    
  def process1(l: List[String]): Unit = {
    l.foreach(new Function1[String, Unit] {
      val eta = Register.serviceInst
      def apply(x: String) = eta.process(x)
    })
  }      
}

这篇关于Scala编译:匿名函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆