scala泛型方法覆盖

标签 scala overriding generic-method

我有一个抽象类:

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 的返回值(或 bar1bar2 的参数)在你所知道的关于你的对象的所有设置中(假设它被命名为 obj )是它是一个 Foo ,您需要使用类型 obj.T作为变量的类型。

关于scala泛型方法覆盖,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4626904/

相关文章:

Scala 方法中变量名不明确

scala - 为 Scala IDE 配置 Scala 调试器

c# - Moq It.IsAnyType 不适用于具有泛型类型返回任务的 Func

c++ - 使用 'virtual' 和 'override' 关键字声明重写方法是好是坏?

c# - 不同属性的通用 foreach 循环

java - 如何在静态泛型工厂方法中避免 "Type mismatch"?

scala - 按名称获取已注册的 Spark Accumulator

scala - 如何从 Scala API 文档中确定所需的参数?

javascript - 重写node.js中的方法

c++虚拟关键字与覆盖函数