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.

0 0 votes
Article Rating

Related articles

Mobile App Development Services

Mobile App Development - Android mobile application developer -...

15 Upbeat IDE for developing Android App

IDE for developing android Application abbreviated as Integrated development...

How to Enable WhatsApp Payment

WhatsApp Pay has finally been given regulatory approval by...

WhatsApp Payment Launch in Brazil

Facebook's WhatsApp messaging service rolled out a system across...

Case Studies

Compass Music Platform

A clothing brand wanted to launch a new e-commerce website that would allow customers to browse and purchase their products online. We developed a...

NewsWeek Magazine

A clothing brand wanted to launch a new e-commerce website that would allow customers to browse and purchase their products online. We developed a...

Beauty & Makeup Shop

A clothing brand wanted to launch a new e-commerce website that would allow customers to browse and purchase their products online. We developed a...
0
Would love your thoughts, please comment.x
()
x