Class Properties and Accessors
Explore how Kotlin class properties use accessors like getters and setters to enforce encapsulation and manage data. Understand custom accessors, visibility control, and how properties differ from fields. Learn to apply these concepts to create clean, maintainable Kotlin classes and avoid common pitfalls like infinite recursion.
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
thisfieldSetter: The function that is used to set new values for the
thisfield
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.
Note: The
@Suppress("UNUSED_PARAMETER")annotation suppresses warnings about unused parameters in Kotlin code. It instructs the compiler to ignore warnings about declared but unused parameters. ...