![]() |
VOOZH | about |
In Kotlin, properties are a core feature of the language, providing a clean and concise way to encapsulate fields while maintaining control over how values are accessed or modified. Each property can have getters and setters, which are automatically generated but can be customized as needed.
A property in Kotlin can be declared using either the var or val keyword:
Syntax of Property
var <propertyName>: <PropertyType> = <initializer>
get() = field // Optional getter
set(value) { // Optional setter
field = value
}
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:
Example of Mutable and Immutable Property:
fun main(args: Array<String>) {
var x: Int = 0 // Mutable property
val y: Int = 1 // Immutable property
x = 2 // OK: x is mutable
y = 0 // Error: y is read-only
}
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.
In Kotlin,
By default, Kotlin automatically generates a getter for val and both getter and setter for var. However, you can customize these as needed.
class Company {
var name: String = "DefaultValue"
}
The above code is equivalent to this code:
class Company {
var name: String = "DefaultValue"
get() = field
set(value) {
field = value
}
}
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 -
fun main() {
val company = Company()
company.name = "GeeksforGeeks" // Calls setter
println(company.name) // Calls getter
}
Example of Default Setter and Getter
Output:
GeeksforGeeksWe have noticed these two identifiers in the above program.
If we want the get method in public access, we can write this code:
var name: String = ""
private set
And, we can set the name only in a method inside the class because of private modifier near set accessor. Example to set the value by using a method inside a class.
Output:
Initial name: abc
Updated name: GeeksforGeeks
Explanation:
Here, the set accessor is marked as private, so it cannot be accessed or modified from outside the class, but can still be updated internally via a method.
Output:
praveenruhil1993@gmail.com
Geeks@123
25
M
Here, the custom getter for email ensures the returned value is always lowercase. The custom setter for password validates the length before assignment, and the custom setter for age ensures only positive values are accepted.