In some code requiring subclassing of inner traits/classes I’m having trouble successfully implementing an abstract method, apparently because my type signature doesn’t match. For example:
trait Outer {
trait Inner
def score(i:Inner): Double
}
class Outer2 extends Outer {
class Inner extends super.Inner
def score(i:Inner) = 0.0
}
You might imagine that Outer2.score doesn’t successfully implement Outer.score because the type Outer2.this.Inner doesn’t match Outer.this.Inner. But the compilation error message from scala-2.9.0.1 doesn’t indicate this. It says:
error: class Outer2 needs to be abstract, since method score in trait Outer
of type (i: Outer2.this.Inner)Double is not defined
(Note that Outer.this.Inner does not match Outer2.this.Inner)
It says it is expecting an argument of type Outer2.this.Inner! This is actually exactly the behavior I want. But why doesn’t my second score definition successfully match the type of the abstract method?
I tried to make things more clear for the compiler with the following alternative code, but I get similarly confusing error messages for it also.
trait Outer[This<:Outer[This]] {
this: This =>
trait Inner
def score(i:This#Inner): Double
}
class Outer2 extends Outer[Outer2] {
class Inner extends super.Inner
def score(i:Outer2#Inner) = 0.0
}
You can’t refine the types of method parameters in an overriding method.
This works:
Consider if the compiler allowed your code:
An overriding method may have a more specific return type, as this doesn’t lead to unsound code. (At the JVM level, where the return types is included in the method signature, Bridge Methods are created to allow callers to program against the signature in the superclass and dispatch to the implementation in the subclass.)