Scala 特征如何编译成 Java 字节码? [英] How are Scala traits compiled into Java bytecode?

查看:47
本文介绍了Scala 特征如何编译成 Java 字节码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Scala 已经有一段时间了,我知道 trait 可以充当接口和抽象类的 Scala 等价物.trait 究竟是如何编译成 Java 字节码的?

I have played around with Scala for a while now, and I know that traits can act as the Scala equivalent of both interfaces and abstract classes. How exactly are traits compiled into Java bytecode?

我发现了一些简短的解释,这些特征在可能的情况下与 Java 接口完全一样编译,否则与附加类接口.然而,我仍然不明白,Scala 是如何实现类线性化的,这是 Java 中没有的特性.

I found some short explanations that stated traits are compiled exactly like Java interfaces when possible, and interfaces with an additional class otherwise. I still don't understand, however, how Scala achieves class linearization, a feature not available in Java.

是否有很好的来源解释特征如何编译为 Java 字节码?

Is there a good source explaining how traits compile to Java bytecode?

推荐答案

我不是专家,但我的理解是:

I'm not an expert, but here is my understanding:

Traits 被编译成一个接口和对应的类.

Traits are compiled into an interface and corresponding class.

trait Foo {
  def bar = { println("bar!") }
}

变成等价于...

public interface Foo {
  public void bar();
}

public class Foo$class {
  public static void bar(Foo self) { println("bar!"); }
}

这就留下了一个问题:Foo$class 中的静态 bar 方法是如何被调用的?这个魔法是由编译器在 Foo trait 混入的类中完成的.

Which leaves the question: How does the static bar method in Foo$class get called? This magic is done by the compiler in the class that the Foo trait is mixed into.

class Baz extends Foo

变得像……

public class Baz implements Foo {
  public void bar() { Foo$class.bar(this); }
}

类线性化只是根据语言规范中定义的线性化规则实现了相应版本的方法(调用Xxxx$class类中的静态方法).

Class linearization just implements the appropriate version of the method (calling the static method in the Xxxx$class class) according to the linearization rules defined in the language specification.

这篇关于Scala 特征如何编译成 Java 字节码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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