Consider the following simple trait
trait Parent {
def x: Int = 0
}
Now consider an implementing class that wishes to define x to be mutable.
class Child extends Parent {
var x: Int = 1
}
This won't work, because
7 | var x: Int = 1
| ^
| error overriding method x in trait Parent of type => Int;
| variable x of type Int needs `override` modifier
But the override modifier won't work either. If I write
override var x: Int = 1
I get
7 | override var x: Int = 1
| ^
| setter x_= overrides nothing
This makes sense. var is implicitly defining two methods, one called x and one called x_=. The former requires the override modifier but the latter is not an override.
Obviously, I can implement this with a private var and explicit methods
class Child extends Parent {
private var _x: Int = 1
override def x: Int = _x
def x_=(value: Int): Unit = {
_x = value
}
}
But this seems very high in getter/setter boilerplate for Scala's tastes. Is there a way to mark var x as partially overriding the parent's body?