3 - Setters and Getters
3 - Setters and Getters
Syntax of Property
Here, the property initializer, getter and setter are optional. We can also omit
the 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:
In the above code, we are trying to assign a value again to ‘y’ but it shows a
compile time error because it cannot accept the change.
Setters and Getters
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
we shall initialize it with some default value.
class Company {
var name: String = "Defaultvalue"
}
class Company {
var name: String = "defaultvalue"
get() = field // getter
set(value) { field = value } // setter
}
We instantiate an object ‘c’ of the class ‘Company {…}’. When we initialize the
‘name’ property, it is passed to the setter’s parameter value and sets the ‘field’
to value. When we are trying to access name property of the object, we get
field because of this code get() = field. We can get or set the properties of an
object of the class using the dot(.) notation–
val c = Company()
c.name = "GeeksforGeeks" // access setter
println(c.name) // access getter (Output: GeeksforGeeks)
Kotlin
class Company {
var name: String = ""
get() = field // getter
set(value) { // setter
field = value
}
}
fun main(args: Array<String>) {
val c = Company()
c.name = "GeeksforGeeks" // access setter
println(c.name) // access getter
}
Output:
GeeksforGeeks
If we want the get method in public access, we can write this code:
And, we can set the name only in a method inside the class because of private
modifier near set accessor. Kotlin program to set the value by using a method
inside a class.
Kotlin
class Company () {
var name: String = "abc"
private set
Output:
Explanation:
Here, we have used private modifier with set. First instantiate an object of
class Company() and access the property name using ${c.name}. Then, we
pass the name “GeeksforGeeks” as parameter in function defined inside class.
The name property updates with new name and access again.
Custom Setter and Getter
Kotlin
class Registration( email: String, pwd: String, age: Int , gender: Char) {
println("${geek.email_id}")
geek.email_id = "[email protected]"
println("${geek.email_id}")
println("${geek.password}")
println("${geek.age}")
println("${geek.gender}")