This page is no longer maintained — Please continue to the home page at www.scala-lang.org

overriding java methods with variance annotations

No replies
Adam Crain
Joined: 2011-05-17,
User offline. Last seen 42 years 45 weeks ago.

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?

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland