Why should we use the 'override' key word in Kotlin for abstact class members?

Viewed 158

If the base class has an abstract method or property, than these members must be overriden in the child class. The documentation says that i must use key word 'override' every time for such members, because i must implement methods or initialize properties in the child class. For example:

abstract class Dwelling {
    abstract val buildingMaterial: String

    abstract fun hasRoom() : Boolean
}

class RoundHut : Dwelling() {
    override val buildingMaterial = "Stone"

    override fun hasRoom() : Boolean {
         return true
    }
}

If an abstract method and a property must be overriden and implemented in child class any way (and compiler know this), than why we should write 'override' key word every time?

1 Answers

When you find yourself reading and understanding the implementing class, you have the explicit information that you're currently investigating an overridden one as it's explicitly marked as such. Kotlin likes to make things explicit and the documentation states

[...] we stick to making things explicit in Kotlin. So, Kotlin requires explicit modifiers for overridable members (we call them open) and for overrides

Java has an @Override annotation that is optional and not used by everyone although it has been considered a best practice (even as per Effective Java). Kotlin goes one step further by making it a compiler-enforced requirement.

Related