Getters and Setters

Reading Time: 3 minutes

Getters and Setters are used to effectively protect your data, particularly when creating classes. For each instance variable, a getter method returns its value while a setter method sets or updates its value. Getters and setters are also known as accessors and mutators, respectively.

Accessing properties directly is not a good practice.

Sometimes we need to check the value in case of an invalid input, or do some other data validation or calculation before assigning or accessing the property value.

Let’s say we have a User class with an age property.


The object’s property can be easily assigned to an invalid value.

Getters and setters allow flexibility in property access. The setter is defined using the set keyword and allows to define behavior when a value is assigned to the property.

Kotlin automatically creates the getters (val and var) and setters (val), but in some cases we have to use them.

Backing field

Backing field helps you refer to the property inside the getter and setter methods. This is required because if you use the property directly inside the getter or setter then you’ll run into a recursive call which will generate a StackOverflowError.

Every time a client code assigns a new value to the age property, the setter is called with the value as its argument. Immutable variables (val) cannot have a setter.

The code checks whether the value is greater than 0, and only then assigns it to the property.

The following code will output 0, as the value -12 won’t be assigned to the age property.

The user is 0 years old.

A getter, on the contrary, is called every time the value of a property is read.

We can, for example, add 2 to the value of the age property when it is accessed.


The field keyword refers to the property (age in this case). A property can have both, a getter and a setter.

Custom Setter and Getter

Custom Setter and Getter


I hope the description was understandable and clear. But if you have still questions, then leave me comments below! 😉

Have a nice a day! 🙂  



Follow and like us:
Click to rate this post!
[Total: 0 Average: 0]

Leave a comment

stay informed!

Subscribe to receive exclusive content and notifications