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.

Example

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 = "www.tutorialspoint.com"
   var city: String = "Hyderabad"
   val state: String = "Telangana"
}

Output

Once executed, it will yield the following output.

Name is -> www.tutorialspoint.com
City is -> Hyderabad
State is -> Telangana
raja
Updated on 16-Mar-2022 12:12:45

Advertisements