在此示例中,我无法理解 Scalac 的错误消息:
Bean.java
public class Bean {
static public class Attribute<T> {
public final String name;
public Attribute(String name) {this.name = name;}
// equals and hashcode omitted for simplicity
}
public <T> void set(Attribute<T> attribute, T value) {}
public static Attribute<Long> AGE = new Attribute<Long>("age");
}
测试.scala
object Test {
def test() {
val bean = new Bean();
bean.set(Bean.AGE, 2L);
}
}
编译得到这个(用 scalac 2.9.2 试过):
Test.scala:4: error: type mismatch;
found : Bean.Attribute[java.lang.Long]
required: Bean.Attribute[Any]
Note: java.lang.Long <: Any, but Java-defined class Attribute is invariant in type T.
You may wish to investigate a wildcard type such as `_ <: Any`. (SLS 3.2.10)
bean.set(Bean.AGE, 2L);
^
one error found
为什么需要 Attribute[Any]?在 Java 中做同样的事情很好
谢谢