Creating getter setters in Kotlin
If you have worked with Java, you probably know what a getter-setter is. Java has fields and getter-setters are the methods that are used to access (getter) and modify (setter) member variables. They are an essential part of encapsulation (one of the design principles).
However, in Kotlin, we don't have any fields, but we have properties instead. A property can have a custom implementation of an accessor and a mutator. In this recipe, we will see how we can implement custom accessors and mutators.
Getting ready
We will be using IntelliJ IDEA to write and execute our code. You can use whatever development environment you are comfortable with. We will be using examples to understand the custom getter-setters of Kotlin.
How to do it...
Let's follow these steps to understand how custom getter-setters work in Kotlin:
- The syntax of a Kotlin
property
looks like this:
var<propertyName>[: <PropertyType>] [=<property_initializer>] [<getter>] [<...