Subscribe for notification
Categories: Android Tutorial

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.

Sponsored
SyncSaS

SyncSaS Technologies is specialized in creating and designing customized software. We have our own team that will be in charge of developing your softwares.

Share
Published by

Recent Posts

Adsense Updated Dashboard

Changes in Adsense Dashboard Recently you might have seen few changes in Adsense dashboard, these…

4 weeks ago

Guide Book For Google Adsense

With my experience in working as AdSense publisher, I have written many articles, tutorials for…

4 weeks ago

How to manage Google Adsense to get High CPC

Manage Adsense for High CPC CPC (Cost per click) in simple words the CPC is…

4 weeks ago

Google Adsense Introduce page level ads

If you are already the publisher of Google Adsense account then now its time to…

4 weeks ago