Scala:强制子类覆盖方法的继承实现



我想定义一个特征,强制其子类型覆盖toString方法。 我能做到吗?

在更通用的情况下:

trait Old {
def foo: String = "oldFoo"
}
trait New {
//some statement which would result in "oldFoo" disappearing 
}
trait New1 extend New {
def foo: String = "new1Foo"
} //should compile
trait New2 extend New //shouldn't compile

我认为你想做的事情是不可能的,但这种解决方法可能有效

trait Old {
def foo: String = "oldFoo"
}
trait New extends Old {
override final def foo: String = newFoo
def newFoo: String
}
class New1 extends New {
override def newFoo: String = "new1Foo"
} // Compiles
class New2 extends New // Don't compiles
trait NewExtra extends New // Compiles, but any sub class of NewExtra is required to implement newFoo

最新更新