Syncsas Tutorials & Blog

Using Explicit Getter & Setter for Kotlin Properties

Before you learn about getters and setter, be sure to check Kotlin class and objects. I started developing Android apps in Java where encapsulation of object-oriented programming was achieved through declaring variables as private fields with their getter and setter as public methods. The moment I converted my Java code to Kotlin, it replaced each variable along with its getter and setter with just a single line of code. Although I was amazed at how can a single line of code replace the complete variable with the same functionality, but later on understanding it, I started liking writing the code in Kotlin. Let’s understand how it works in Kotlin.

In programming, getters are used for getting value of the property. Similarly, setters are used for setting value of the property. Variable having a class level scope (member variables) which are declared inside the class but outside the methods or functions is called as Property in Kotlin. They are declared with var keyword for a mutable one and with val keyword for a read-only/nonmutable one.

In Kotlin, getters and setters are optional and are auto-generated if you do not create them in your program.Here, property initializer, getter and setter are optional. We can also omit property type if it can be inferred from the initializer.
The syntax of a read-only or immutable property declaration differs from a mutable one in two ways:
starts with val instead of var, and does not allow a setter. In Kotlin, setter is used to set the value of any variable and getter is used to get the value. Getters and setters are auto-generated in the code.
Let’s define a property name in a class company. The data type of name is String and initialize it with some default value.

Exit mobile version