我想定义一个特征,强制其子类型重写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
答案 0 :(得分:2)
我不认为您想做的事是可行的,但是这种解决方法可以工作
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