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 开发者_如何学Goin 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?
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.
精彩评论