开发者

value foo in class MyJavaClass of type java.lang.String has incompatible type mixing in Java class and Scala trait

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜