Scala inner types as abstract method arguments
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:
class Outer2 extends Outer {
def score(i: super[Outer].Inner) = 0.0
// Or just:
// def score(i: super.Inner) = 0
}
Consider if the compiler allowed your code:
trait Outer {
trait Inner
def score(i:Inner): Double
}
class Outer2 extends Outer {
class Inner extends super.Inner { def foo = "!" }
def score(i:Inner) = { i.foo; 0.0 }
// !!! unsafe, no `foo` method
score(new super[Outer].Inner{})
}
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.)
这可能是一个合适的解决方法,具体要求取决于:
trait Outer {
trait InnerI
type Inner <: InnerI
def score(i:Inner): Double
}
class Outer2 extends Outer {
class InnerI extends super.InnerI
type Inner = InnerI
def score(i:Inner) = 0.0
}
链接地址: http://www.djcxy.com/p/66206.html
上一篇: 通过函数参数的协方差
下一篇: Scala内部类型为抽象方法参数