【发布时间】:2021-06-25 14:14:27
【问题描述】:
我想在 Scala trait 中定义一个方法,其中方法的参数和返回类型对应于扩展该 trait 的同一个具体类。我尝试过类似以下的方法:
trait A {
def foo(obj: this.type): this.type
}
final case class B(val bar: Int) extends A {
override def foo(obj: B): B = {
B(obj.bar + this.bar)
}
}
object Main {
def main(args: Array[String]) = {
val b1 = new B(0)
val b2 = new B(0)
val b3: B = b1.foo(b2)
}
}
但是,尝试编译此代码会出现以下错误:
Test.scala:5: error: class B needs to be abstract. Missing implementation for:
def foo(obj: B.this.type): B.this.type // inherited from trait A
case class B(val bar: Int) extends A {
^
Test.scala:6: error: method foo overrides nothing.
Note: the super classes of class B contain the following, non final members named foo:
def foo: ((obj: _1.type): _1.type) forSome { val _1: B }
override def foo(obj: B): B = {
^
2 errors
显然我对这里的 Scala 类型系统有一些误解。 foo 在B 类中的签名是我想要的,但我不知道如何正确定义A 中的方法(或者如果这甚至可能)。 this question 似乎在问一些非常相似的问题,但我没有立即看到答案如何适用于我的情况。
【问题讨论】:
-
this.type的住户永远只有一个,那就是this。您的“覆盖”说“我将采用 B 并返回一些,也许是其他的 B 实例”,这不够具体。 -
@OlegPyzhcov 我确实想返回一些,也许是 B 的其他实例。我意识到我的示例可能不清楚,因为我不知道 foo 方法可能是什么样子。我更新了示例。
标签: scala inheritance typing