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

时间:2018-09-21 13:47:29

标签: scala override

我想定义一个特征,强制其子类型重写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

1 个答案:

答案 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