我最近在使用 Spring Security 进行开发时遇到了一个问题。它有一个接口(interface)GrantedAuthority
带有以下签名:
public interface GrantedAuthority extends Serializable, Comparable
而对于 Java 1.5 及更高版本,接口(interface)
Comparable
接受类型参数 T
,在 Spring Security 库中省略(显然是为了 JVM 1.4 兼容性)。所以我正在尝试实现
GrantedAuthority
在斯卡拉。class Role extends GrantedAuthority {
. . .
def compareTo(obj: Any): Int = obj match {
case (r: Role) => r.toString.compareTo(this.toString)
case _ => -1
}
}
它不编译:
error: class Role needs to be abstract, since method compareTo in trait Comparable of type (T)Int is not defined
如何在 Scala 中实现这样的接口(interface)?
最佳答案
Java 泛型的互操作问题(至少)有两种形式:
Comparable
被视为存在类型 Comparable[_]
.有时你可以摆脱这个问题。但是,我看不到实现 def compareTo(other: _) = ...
的方法在这种情况下。 Comparable[T]
具有逆变 scala 特征 Ordering[-T]
除非您使用 @uncheckedVariance
否则会发生错误注解。 ( Discussion on the mailing list ) 我建议您尝试升级到针对 Java 1.5 编译的 Spring 3.x。如果这不可能,写一个基类
BaseGrantedAuthority
在 Java 中实现 compareTo
并委托(delegate)给可以在 Scala 中实现的模板方法。
关于inheritance - 实现不安全的 Java 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2258718/