In Kotlin, overriding a property allows a subclass to redefine the accessors (getters and setters) of a property declared in a superclass or interface. Because Kotlin classes and members areDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
final by default, the base property must be explicitly marked with the open modifier, and the derived property must be marked with the override modifier. Overriding a property strictly overrides its accessors; it does not override or skip the base class initialization logic, which still executes when the class is instantiated.
Basic Syntax
To override a property, the derived class must declare a property with the same name and a compatible type, prefixed with theoverride keyword. When an overridden property is initialized in the subclass, it creates a new backing field and a new getter in the subclass that reads from this new field.
Primary Constructor Overriding
Properties can be overridden directly within the primary constructor of the derived class. This is a concise syntax for declaring and initializing overridden properties.Mutability Rules (val vs var)
Kotlin enforces strict rules regarding property mutability during inheritance, based on the underlying accessors generated by the compiler:
- Overriding
valwithvaris permitted: Avalproperty declares only a getter. Overriding it with avarprovides a new getter and a new setter in the derived class. - Overriding
varwithvalis prohibited: Avarproperty requires both a getter and a setter. Overriding it with avalwould illegally remove the setter contract defined by the superclass.
Overriding Accessors
Instead of assigning a backing field value directly, you can override the custom getter (and setter, if applicable) of the property. You can also access the superclass implementation using thesuper keyword.
Overriding with Property Delegation
An overridden property can be implemented using Kotlin property delegates (such aslazy, observable, or custom delegates).
Type Covariance in Overrides
When overriding a property, the type of the overriding property must be a subtype of the overridden property’s type. This covariance applies to read-only (val) properties.
Master Kotlin with Deep Grasping Methodology!Learn More





