Scala通用方法覆盖 [英] scala generic method overriding
问题描述
我有一个抽象类:
abstract class Foo(...){
def bar1(f : Foo) : Boolean
def bar2(f : Foo) : Foo
}
多个类扩展了Foo并覆盖了方法
multiple classes extend Foo and override the methods
class FooImpl(...) extends Foo{
override def bar1(f : Foo) : Boolean {
...
}
override def bar2(f : Foo) : Foo {
...
}
}
是否可以使用泛型(或其他方法)使重写方法具有实现它的子类的参数类型?像这样:
Is it possible, using generics (or something) to make the overriding methods have the parametertype of the subclass implementing it? Like this :
class FooImpl(...) extends Foo{
override def bar1(f : FooImpl) : Boolean {
...
}
override def bar2(f : FooImpl) : FooImpl {
...
}
}
我在考虑以下内容,但这似乎没有效果...
I was thinking something along the line of the following, but that didn't seem to work...
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
共享为超类,但在设置中将bar2
的返回值(或bar1
或bar2
的参数)保留为您了解对象(假设它名为obj
)是它是Foo
,您需要使用类型obj.T
作为变量的类型.
In this version, different subclasses of Foo
all share Foo
as a superclass, but to hold the return value of bar2
(or the parameters to bar1
or bar2
) in a setting where all you know about your object (let's say it's named obj
) is that it's a Foo
, you need to use the type obj.T
as the type of the variable.
这篇关于Scala通用方法覆盖的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!