Kotlin | Class Properties and Custom Accessors
The basic and most important idea of a class is Encapsulation. It is a property to encapsulate code and data, into a single entity. In Java, the data are stored in the fields and these are mostly private. So, accessor methods – a getter and a setter are provided to let the clients of the given class access the data. For sending notifications about the change or validating the passed value, additional logic is also present in the setter.
It is the combination of accessories and the fields in the case of Java. In the case of Kotlin, properties are meant to be a first-class language feature. These features replace fields and accessor methods. A property in a class is declared the same as declaring a variable with val and var keywords. A property declared as var is mutable and thus, can be changed.
Defining a class:
Readable Property: Generates a field and a trivial getter
Writable Property: A getter, a setter, and a field
Basically what happens is that the declaration of the property declares the related accessors (both setter and getter for writable and getter for readable property). A field stores the value.
Let’s see the class usage
In Kotlin, the constructor can be called without a new keyword. Instead of invoking the getter, the property is referenced directly. The logic remains the same and the code is much more concise. Setters of mutable property works in a similar manner.
Custom implementation of property accessor.
The property isSquare needs no field to store the value. It only has a custom getter with the implementation provided. Every time the property is accessed, the value is computed.