- About Scala
- Documentation
- Code Examples
- Software
- Scala Developers
overriding java methods with variance annotations
Tue, 2011-05-17, 15:37
Hi,
Our project requires that we document some external interfaces in
java, but I'm having some trouble overriding things with variance
annotations. I have prepared a simplified example.
Ultimately, in Scala, I need something that is an AnyRef so that I can
use the getClass method. This is a contrived example, but for
arguments sake:
trait Gettable {
def get[A <: AnyRef](value : A) : String = value.getClass.toString
}
Now I want to define this interface in Java:
interface IGettable {
String get(T value);
}
and implement it in scala:
Class GettableImpl extends IGettable {
A get[A <: java.lang.Object](T value) = value.getClass.
}
Object has a getClass method, so this should work right? It doesn't
compile:
error: overriding method get in trait IGet of type [T](request:
T)java.lang.String;
method get has incompatible type
final override def get[A <: Object](request: A) : String =
request.toString
However, if I substitude java.lang.Object for some other class
everywhere:
class SomeBaseClass {
}
interface IGettable {
String get(T value);
}
class GettableImpl extends IGettable {
A get[A <: SomeBaseClass](T value) = value.getClass.
}
It all compiles just fine. What makes object so special. Ideas?