[英]How to implement Java interface that extends Comparable with no specific type in Scala?
I am using a Java library in my Scala project which has an interface that looks like this:我在我的 Scala 项目中使用了 Java 库,它的界面如下所示:
public interface A extends Comparable {
String getSomething();
}
Note how the library implementation does not specify any specific type for Java's Comparable<T>
interface.请注意库实现如何没有为 Java 的
Comparable<T>
接口指定任何特定类型。
In my Scala code I want to create an instance of A like so:在我的 Scala 代码中,我想创建一个 A 的实例,如下所示:
object AFactory {
def getA: A = new A {
override def getSomething: String = "test"
override def compareTo(o: ???): Int = -1
}
}
Unfortunately, I am not sure what type to specify for ???
不幸的是,我不确定要指定什么类型
???
. . Does anyone know how can I implement this interface and get it to compile?
有谁知道我怎样才能实现这个接口并让它编译?
There is no direct way to do it.没有直接的方法可以做到这一点。 One way to make you code run against pre-java5 code, is to have Java bridge methods:
让您的代码针对 pre-java5 代码运行的一种方法是使用 Java 桥接方法:
public abstract class B implements A {
@Override
public int compareTo(Object o) {
return 0;
}
}
object AFactory {
def getA: A = new B {
override def getSomething: String = "test"
}
}
If you not want to have the compareTo
implemented in Java.如果您不想在 Java 中实现
compareTo
。 You could may be introduce a bridge method and implement the bridge method in scala:您可以引入桥接方法并在 scala 中实现桥接方法:
public abstract class B implements A {
@Override
public int compareTo(Object o) {
return compareToBridge(o);
}
protected abstract int compareToBridge(Object o);
}
object AFactory {
def getA: A = new B {
override def getSomething: String = "test"
override def compareToBridge(o: Any): Int = ???
}
}
Without using bridge methods, I dont think there is a nicer way of solving this problem.如果不使用桥接方法,我认为没有更好的方法来解决这个问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.