Jan*_*ten 19 overriding scala generic-method
我有一个抽象类:
abstract class Foo(...){
def bar1(f : Foo) : Boolean
def bar2(f : Foo) : Foo
}
Run Code Online (Sandbox Code Playgroud)
多个类扩展Foo并覆盖方法
class FooImpl(...) extends Foo{
override def bar1(f : Foo) : Boolean {
...
}
override def bar2(f : Foo) : Foo {
...
}
}
Run Code Online (Sandbox Code Playgroud)
有可能,使用泛型(或其他东西)使重写方法具有实现它的子类的参数类型吗?像这样 :
class FooImpl(...) extends Foo{
override def bar1(f : FooImpl) : Boolean {
...
}
override def bar2(f : FooImpl) : FooImpl {
...
}
}
Run Code Online (Sandbox Code Playgroud)
我正在思考下面的内容,但这似乎不起作用......
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{
...
}
}
Run Code Online (Sandbox Code Playgroud)
任何帮助深表感谢!
谢谢.
Ken*_*oom 21
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
}
Run Code Online (Sandbox Code Playgroud)
在这个版本中,Foo
所有不同的子类都Foo
作为超类共享,但是在一个设置中保存bar2
(或参数为bar1
或bar2
)的返回值,你所知道的对象(假设它的名字obj
)是你的a Foo
,你需要使用类型obj.T
作为变量的类型.
Lan*_*dei 12
为了使Ken Blum的第二个版本更好一点,你可以使用自我类型:
abstract class Foo[T] { self:T =>
def bar1(f:T):Boolean
def bar2(f:T):T
}
class FooImpl extends Foo[FooImpl]{
override def bar1(f:FooImpl) = true
override def bar2(f:FooImpl) = f
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
21954 次 |
最近记录: |