I have an abstract base class with a property that performs a certain validation. The base class doesn’t allow certain mutations (it could be completely immutable). A derived class, however, does allow to change things that are immutable in the base class. This is achieved by overriding the property with a public setter. But that would by default override the base class setter implementation performing the validation. So I call the setter of the base class in the overriding setter.
abstract class ImmutableBase(name: String) {
open var name = name
protected set(name) {
require(name.isNotEmpty()) { "'name' must not be empty." }
field = name
}
}
class MutableDerived(name: String) : ImmutableBase(name) {
override var name = name
set(name) {
super.name = name
}
}
fun main(vararg args: String) {
MutableDerived("")
}
However IntelliJ warns me about “Existing backing field is not assigned by the setter” and it doesn’t feel good to me because it is a bit error prone.
Is there a better idea to solve this issue?