我有两个从抽象基类继承的案例类。我想在抽象基类上定义一些方法,这些方法使用继承案例类上的复制方法(因此返回子类的实例。)有没有办法使用自我类型来做到这一点?
示例代码:
abstract class BaseClass(a: String, b: Int) {
this: case class => //not legal, but I'm looking for something similar
def doubleB(newB: Int) = this.copy(b = b * 2) //doesn't work because BaseClass has no copy
}
case class HasC(a: String, b: Int, c: Boolean) extends BaseClass(a, b) {
def doesStuffWithC(newC: Boolean) = {
...
}
}
case class HasD(a: String, b: Int, D: Double) extends BaseClass(a, b) {
def doesStuffWithD(newD: Double) = {
...
}
}
由于这个问题,我已经弄清楚了如何获得我想要的结果: How to use Scala's this typing, abstract types, etc. to implement a Self type? 但它涉及向 BaseClass 添加一个 makeCopy 方法,并在每个子案例类中调用 copy 来覆盖它,并且语法(尤其是对于 Self 类型)相当混乱。有没有办法用 Scala 的内置自键入来做到这一点?