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

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

问题描述

我已经和Scala玩了一段时间了,我知道特征可以充当接口和抽象类的Scala等效项。

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 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方法如何被叫?

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天全站免登陆