我有一个抽象类:
abstract class Foo(...){
def bar1(f : Foo) : Boolean
def bar2(f : Foo) : Foo
}
多个类扩展 Foo 并覆盖方法
class FooImpl(...) extends Foo{
override def bar1(f : Foo) : Boolean {
...
}
override def bar2(f : Foo) : Foo {
...
}
}
是否有可能使用泛型(或其他东西)使覆盖方法具有实现它的子类的参数类型?像这样 :
class FooImpl(...) extends Foo{
override def bar1(f : FooImpl) : Boolean {
...
}
override def bar2(f : FooImpl) : FooImpl {
...
}
}
我正在考虑以下内容,但这似乎不起作用......
abstract class Foo(...){
def bar1[T <: Foo](f : T) : Boolean
def bar2[T <: Foo](f : T) : T
}
class FooImpl(...) extends Foo{
override def bar1[FooImpl](f : FooImpl) : Boolean {
...
}
override def bar2[FooImpl](f : FooImpl) : FooImpl{
...
}
}
任何帮助深表感谢!
谢谢你。
最佳答案
abstract class Foo{
type T <: Foo
def bar1(f:T):Boolean
def bar2(f:T):T
}
class FooImpl extends Foo{
type T = FooImpl
override def bar1(f:FooImpl) = true
override def bar2(f:FooImpl) = f
}
在这个版本中,
Foo
的不同子类全部分享Foo
作为父类(super class),但要保存 bar2
的返回值(或 bar1
或 bar2
的参数)在你所知道的关于你的对象的所有设置中(假设它被命名为 obj
)是它是一个 Foo
,您需要使用类型 obj.T
作为变量的类型。
关于scala泛型方法覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4626904/