Kotlin Getters and Setters
In Kotlin, you can define getters and setters for class properties using the get
and set
keywords. Getters and setters allow you to control access to the properties of an object and add logic that can be executed when the properties are accessed or modified.
Here's an example of a class with a private property and a public getter and setter:
class Person { private var _age: Int = 0 var age: Int get() = _age set(value) { if (value >= 0) { _age = value } else { throw IllegalArgumentException("Age must be non-negative.") } } }Source:www.theitroad.com
In this example, we have defined a class called Person
with a private property _age
of type Int
. We have also defined a public property age
with a custom getter and setter. The getter simply returns the value of _age
, while the setter first checks if the new value is non-negative, and if so, sets the value of _age
. If the new value is negative, the setter throws an IllegalArgumentException
.
To use the age
property, you can create an instance of the Person
class and set or get the value of the age
property:
val person = Person() person.age = 30 println(person.age) // prints 30
In this example, we create an instance of the Person
class and set the value of the age
property to 30 using the setter. We then print the value of the age
property using the getter, which prints "30" to the console.
Kotlin also provides a shorthand syntax for defining properties with getters and setters:
class Person { var age: Int = 0 set(value) { if (value >= 0) { field = value } else { throw IllegalArgumentException("Age must be non-negative.") } } }
In this example, we have defined a public property age
with a custom setter that uses the shorthand syntax for the backing field (field
). The setter performs the same validation as the previous example, but uses the shorthand syntax to set the value of the backing field.
Note that if you define a custom getter or setter for a property, you cannot also define a default value for that property in the constructor. This is because the default value is set by the constructor, whereas the getter and setter are used to access and modify the property after the object has been created. If you need to provide a default value for a property with a custom getter or setter, you can define a separate property with a default value in the constructor, as shown in the previous examples.