Class Properties and Accessors

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 field

  • Setter: 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 boilerplate codeBoilerplate code refers to repetitive and standardized code that is often required for routine tasks, such as defining getters and setters for class properties. It can be seen as code that is necessary but adds little value to the logic of the program.. So, language creators invented a more powerful concept called properties.

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 1200+ tech skills courses.