java.lang.String 类型的类 MyJavaClass 中的值 foo 在 Java 类和 Scala 特征中具有不兼容的类型混合
我有一个 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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为这是因为 Scala 为“公共”变量生成 getter 和 setter - 变量本身始终是私有的,但 scalac 使它们看起来好像可以公开访问。
换句话说,我相信特征中的
val foo: String
声明实际上相当于:所以你需要提供一个实现
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:so you'd need to provide a Java class that implemented the
foo
method, rather than exposing a public variable.