Class Properties and Accessors
Explore Kotlin properties of the class and custom getter/setter methods.
Introduction to class properties
Inside class bodies, we can also define variables. Variables defined inside classes are called fields. There is an important idea known as encapsulation which means that fields should never be used directly from outside the class because if that happens, we lose control over their state. Instead, fields should be used through accessors.
Accessors: Getter and setter
Getter: The function that is used to get the current value of the
this
fieldSetter: The function that is used to set new values for the
this
field
This pattern is highly influential in Java projects, and we can see plenty of getter and setter functions, which are mainly used in classes that hold data. They are needed to achieve encapsulation, however, they also disturb
Remember: A property is a variable in a class that is automatically encapsulated so that it uses a getter and a setter under the hood. In Kotlin, all variables defined inside classes are properties, not fields.
Property accessors
Some languages, like JavaScript, have built-in support for properties, but Java does not. So in Kotlin/JVM, accessor functions are generated for each property: a getter for val
, and a getter and a setter for var
.
Get hands-on with 1400+ tech skills courses.