我有一个抽象的 Scala 类Base
,它有子类Derived1
和Derived2
. Base
定义了一个函数 f(),它返回一个与其实现类相同类型的对象。所以Derived1.f()
返回Derived1
和Derived2.f()
返回Derived2
。我如何在 Scala 中编写这个?
到目前为止,这是我想出的。
package com.github.wpm.cancan
abstract class Base {
def f[C <: Base]: C
}
case class Derived1(x: Int) extends Base {
def f[Derived1] = Derived1(x + 1)
}
case class Derived2(x: Int) extends Base {
def f[Derived2] = Derived2(x + 2)
}
这会产生以下编译器错误:
type mismatch;
[error] found : com.github.wpm.cancan.Derived1
[error] required: Derived1
[error] def f[Derived1] = Derived1(x + 1)
type mismatch;
[error] found : com.github.wpm.cancan.Derived2
[error] required: Derived2
[error] def f[Derived2] = Derived2(x + 2)
这个错误信息让我很困惑,因为我认为com.github.wpm.cancan.Derived1
应该和Derived1
这个上下文中的一样。