特征和接口二进制兼容吗? [英] Are traits and interfaces binary compatible?

查看:91
本文介绍了特征和接口二进制兼容吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很惊讶 Scala 二进制不兼容 。现在,因为在 Java 8 中我们有默认方法实现,它与 trait 几乎相同,我们提供的是在Java代码中使用traits是否安全?我试图自己使用它:

I've just kind of surprised by the fact that Scala is binary incompatible across different releases. Now, since in Java 8 we have default method implementations which is pretty much the same as traits provide us with is it safe to use traits in Java code? I tried to use it myself as this:

trait TestTrait {
  def method(v : Int)
  def concrete(v : Int) = println(v)
}

public class Test implements TestTrait{ // Compile-error. Implement concrete(Int)
    @Override
    public void method(int v) {
        System.out.println(v);
    }
}

但它拒绝编译。编译器抱怨没有输入具体(Int)。虽然我在 TestTrait 中指定了实现。

But it refuses to compile. Compiler complaints about not imlementing concrete(Int). Although I specified the implementation in TestTrait.

推荐答案

当Scala 2.11时编译器编译一个特征,它不会生成一个带有默认方法的接口,因为生成的代码必须使用Java 6.在Scala 2.12(需要Java 8)中它会,因此如果用2.12编译器编译Scala代码,我希望您能够以这种方式从Java中使用它(至少对于像这样的简单情况)。

When the Scala 2.11 compiler compiles a trait, it doesn't generate an interface with default methods, because the generated code has to work with Java 6. In Scala 2.12 (which requires Java 8) it will, so if you compile your Scala code with 2.12 compiler, I expect that you should be able to use it from Java in this way (at least for a simple case like this).

请注意,这样的更改恰恰是不同的Scala版本二进制不兼容:如果你试图使用Scala 2.12中使用Scala 2.11编译的特性,它会尝试调用接口的默认方法,而不是那里。

Note that changes like this are precisely what makes different Scala versions binary incompatible: if you tried to use a trait compiled with Scala 2.11 from Scala 2.12, it would try to call interface's default methods, which aren't there.

这篇关于特征和接口二进制兼容吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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