Getters and Setters in Kotlin

Kotlin Mobile DevelopmentApps/Applications

Properties in Kotlin can be declared either as mutable using the "var" keyword or as read-only using the "val" keyword. Both these types of variables can be referred by their respective names after the method declaration.

In Kotlin, getter() and setter() methods need not be created explicitly. The Kotlin library provides both of them by default.


In this example, we will see how to use the getter() and setter() methods in Kotlin.

fun main(args: Array<String>) {
   // getter()
   println("Name is -> " + Address().name)
   println("City is -> " + Address().city)
   println("State is -> " + Address().state)
class Address {
   // setter()
   var name: String = ""
   var city: String = "Hyderabad"
   val state: String = "Telangana"


Once executed, it will yield the following output.

Name is ->
City is -> Hyderabad
State is -> Telangana
Updated on 16-Mar-2022 12:12:45