I am using a Java library in my Scala project which has an interface that looks like this:
public interface A extends Comparable {
String getSomething();
}
Note how the library implementation does not specify any specific type for Java's Comparable<T>
interface.
In my Scala code I want to create an instance of A like so:
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:
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. You could may be introduce a bridge method and implement the bridge method in 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.