Kotlin Setters and Getters
Properties in Kotlin –
Properties are important part in any programming language. In Kotlin, we can define properties in the same way as we declare another variable. Kotlin properties can declared either as mutable using var
keyword, or as immutable using val
keyword.
Syntax of property –
var <propertyName>[: <PropertyType>] [= <property_initializer>] [<getter>] [<setter>]
Here, property initializer, getter and setter are optional. We can also omit 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:
starts with val instead of var, and does not allow a setter.
fun main(args : Array) { var x: Int = 0 val y: Int = 1 x = 2 // In can be assigned any number of times y = 0 // It can not be assigned again }
In the above code, we are trying to assign a value again to y but it gives compile time error.
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 initialize it with some default value.
class Company { var name: String = "Defaultvalue" }
The above code is equivalent to this code:
class Company { var name: String = "defaultvalue" get() = field // getter set(value) { field = value } // setter }
We instantiate an object c
of the class Company {…} and, when we initialize the name
property, it is passed to the setter’s parameter value and sets 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 program of default setter and getter-
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
value and field identifiers –
We have noticed these two identifiers in the above program.
- value –
Conventionally, we choose the name of the setter parameter is value, but we can choose a different name if we want. The value parameter contains the value that a property is assigned to.
In above program, we have intialized the property name as c.name = “GeeksforGeeks”, the value parameter contains the assigned value “GeeksforGeeks”. - Backing Field (field) –
It helps in storing the property value in memory possible. When we initialize a property with a value, the initialized value is written to the backing field of that property.
In above program, the value is assigned to field and then field is assigned to get().
private modifier –
If we only want 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.
Kotlin program to set the value by using a method inside a class –
class Company () { var name: String = "abc" private set fun myfunc(n: String) { name = n // we set the name here } } fun main(args: Array<String>) { var c = Company() println( "Name of the company is: ${c.name}" ) c.myfunc( "GeeksforGeeks" ) println( "Name of the new comapny is: ${c.name}" ) } |
Output:
Name of the company is: abc Name of the new comapny is: GeeksforGeeks
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
class Registration( email: String, pwd: String, age: Int , gender: Char) { var email_id: String = email // Custom Getter get() { return field.toLowerCase() } var password: String = pwd //Custom Setter set(value){ field = if (value.length > 6 ) value else throw IllegalArgumentException( "Passwords is too small" ) } var age: Int = age // Custom Setter set(value) { field = if (value > 18 ) value else throw IllegalArgumentException( "Age must be 18+" ) } var gender : Char = gender //Custom Setter set (value){ field = if (value == 'M' ) value else throw IllegalArgumentException( "User should be male" ) } } fun main(args: Array<String>) { val geek = Registration( "PRAVEENRUHIL1993@GMAIL.COM" , "Geeks@123" , 25 , 'M' ) println( "${geek.email_id}" ) geek.email_id = "GEEKSFORGEEKS@CAREERS.ORG" println( "${geek.email_id}" ) println( "${geek.password}" ) println( "${geek.age}" ) println( "${geek.gender}" ) // throw IllegalArgumentException("Passwords is too small") geek.password = "abc" // throw IllegalArgumentException("Age should be 18+") geek.age= 5 // throw IllegalArgumentException("User should be male") geek.gender = 'F' } |
Output:
praveenruhil1993@gmail.com geeksforgeeks@careers.org Geeks@123 25 M
Recommended Posts:
- Kotlin Data Types
- Hello World program in Kotlin
- Kotlin | Retrieve Collection Parts
- Destructuring Declarations in Kotlin
- DatePicker in Kotlin
- Kotlin labeled continue
- Introduction to Kotlin
- Kotlin Type Conversion
- Kotlin Exception Handling | try, catch, throw and finally
- Kotlin if-else expression
- Kotlin Environment setup for Command Line
- Kotlin constructor
- Kotlin Environment setup with Intellij IDEA
- Kotlin Nested class and Inner class
- Kotlin Variables
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.