In this article , Lets understand how to use property getters and setters in kotlin
A simple student class as follows
class Student(var studentFirstName: String,
var studentLastName: String = "No Name") {
fun getStudentName(): String {
return "$studentFirstName $studentLastName"
}
fun printStudentName() {
println("$studentFirstName $studentLastName")
}
fun printStudentInfo() {
println("Name:$studentFirstName $studentLastName)
}
}
Now lets add a property to this class and understand the getters and setters behavior
Add a Property
Lets add a property age
to the above class
var age : String= "0"
Now lets modify and print the age
property from the main class
fun main(){
val student = Student("Vignesh", "Prabhu")
println(student.age)
}
Console O/P:
0
Property Getter
Now lets add getter to this age
property as follows
var age = "0"
get() {
return "${getStudentName()}'s age is $field"
}
In the above code , get() is called whenever we access this field . So we have manipulated the value of the property in a way that if we access the property age
, then it will return as follows
fun main(){
val student = Student("Vignesh", "Prabhu")
println(student.age)
}
Console O/P:
Vignesh Prabhu's age is 0
In the above code we can observe that , we we accessed the property age
and printed in the console shows Vignesh Prabhu's age is 0 because in the get method we have added the code return "${getStudentName()}'s age is $field"
.
Here
$field
is called backing field since the contains the value of propertyage
Property Setter
Now lets add setter to this age
property as follows
var age = "0"
get() {...}
set(value) {
field = if (value == "0") {
"unknown"
} else {
value
}
}
In the above code , set(value)
is called whenever we want to modify the property in our own way . value
is nothing but the passed value in the runtime. So lets see how it changes the property if we use this
fun main(){
val student = StudentProperty("Vignesh", "Prabhu")
println(student.age)
student.age = "0"
println(student.age)
}
Console O/P:
Vignesh Prabhu's age is 0
Vignesh Prabhu's age is unknown
As we can observe that when the value 0 is passed to age
property , the set method takes over and manipulates the value wrt to the logic used.
Updated Student class:
class Student(var studentFirstName: String,
var studentLastName: String = "No Name") {
var age = "0"
get() {
return "${getStudentName()}'s age is $field"
}
set(value) {
field = if (value == "0") {
"unknown"
} else {
value
}
}
fun getStudentName(): String {
return "$studentFirstName $studentLastName"
}
fun printStudentName() {
println("$studentFirstName $studentLastName")
}
fun printStudentInfo() {
println("Name:$studentFirstName $studentLastName -------- Age:$age")
}
}
So finally , I hope i made you understand property getter and setter in Kotlin.
Please leave your comments to improve.
Enjoy coding