Kotlin Setter and Getter tutorials with examples
This tutorial explains how to generate Kotlin property setters and getters with examples. Setter and getter are methods for a given property or a field in Kotlin classes
A setter method sets values to a property, while a getter method retrieves or returns the property value.
Generating Setter and Getter in Kotlin
Kotlin declares variables or fields using val and var:
varis used for a mutable variable declaration that can be changed later.valis used for immutable variables that cannot be modified.
Example with var field: By default, Kotlin generates a setter and getter for every property declared in a class. The default modifier for these setters and getters is public.
For example
class Employee {
var name: String = ""
}
This generates the following setter and getter by default:
class Employee {
var name: String = ""
get() {
return field
}
set(value) {
field = value
}
}
Here is an example of calling the setter and getter:
fun main() {
val emp = Employee()
// calling setter
emp.name = "John"
// calling getter
println(emp.name)
}
class Employee {
var name: String = ""
get() {
return field
}
set(value) {
field = value
}
}
If you don’t have a custom implementation in the setter and getter functions, you can skip writing them.
Example with val field
Kotlin, by default, generates only getters for variables declared with val. val variables are immutable; hence, setters are not allowed.
fun main() {
val emp = Employee()
// calling getter
println(emp.name)
}
class Employee {
val name: String = ""
get() {
return field
}
}
If you try to add a setter for the val variable, it throws an error:
Val cannot be reassigned A ‘val’-property cannot have a setter Reassignment of a read-only property via backing field
Public Getter and Private Setter in Kotlin
You can customize the access modifier for these functions.
Here is an example with a public getter and a private setter:
var name: String = "John"
get() {
return name
}
private set(value) {
name = value
}
Conclusion
This tutorial has shown how to generate Kotlin property setters and getters with examples. It covered the concept of setter and getter in Kotlin mutable (var) and immutable (val) variables.
