java.lang.String 类型的类 MyJavaClass 中的值 foo 在 Java 类和 Scala 特征中具有不兼容的类型混合

发布于 2024-11-19 06:19:08 字数 585 浏览 4 评论 0原文

我有一个 Scala 特征

trait MyTrait{  
  val foo: String
  def bar = foo
}

和一个提供 foo 的 Java 类

public class MyJavaClass {
    public final String foo = "hello";
}

现在我尝试混合它们

class MyScalaClass extends MyJavaClass with MyTrait { 
}

,但它无法编译

overriding value foo in trait MyTrait of type String;  value foo in class MyJavaClass of type java.lang.String has incompatible type.

我已经尝试了看似合理的 vals、vars 和 defs 的每种组合,但找不到任何编译此配置的方法。

如何为 Java 类提供特征的 val?

I have a Scala trait

trait MyTrait{  
  val foo: String
  def bar = foo
}

and a Java class that provides foo

public class MyJavaClass {
    public final String foo = "hello";
}

Now I try to mix them

class MyScalaClass extends MyJavaClass with MyTrait { 
}

it won't compile

overriding value foo in trait MyTrait of type String;  value foo in class MyJavaClass of type java.lang.String has incompatible type.

I've tried every combination of vals, vars and defs that seem plausible, but can't find any way of compiling this configuration.

How can I provide a trait's val with a Java class?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夕色琉璃 2024-11-26 06:19:08

我认为这是因为 Scala 为“公共”变量生成 getter 和 setter - 变量本身始终是私有的,但 scalac 使它们看起来好像可以公开访问。

换句话说,我相信特征中的 val foo: String 声明实际上相当于:

// def foo_=(s: String)  // setter - would apply to var declarations
def foo: String      // getter

所以你需要提供一个实现 foo 的 Java 类方法,而不是暴露公共变量

I think this is due to the fact that Scala generates getters and setters for "public" variables - the variables themselves are always private, but scalac makes them look as if they're publically accessible.

In other words, I believe your val foo: String declaration in the trait is actually equivalent to:

// def foo_=(s: String)  // setter - would apply to var declarations
def foo: String      // getter

so you'd need to provide a Java class that implemented the foo method, rather than exposing a public variable.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文