Skip to content
Related Articles

Related Articles

Kotlin Setters and Getters

View Discussion
Improve Article
Save Article
  • Last Updated : 21 Jun, 2022

Properties are an important part of any programming language. In Kotlin, we can define properties in the same way as we declare another variable. Kotlin properties can be declared either as mutable using the var keyword or as immutable using the val keyword.

Syntax of Property  

var <propertyName>[: <PropertyType>] [= <property_initializer>]
    [<getter>]
    [<setter>]

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: 

  1. It starts with val instead of var.
  2. It 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 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"
}

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 {…}’. 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 Program of Default Setter and Getter 

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

Value and Field Identifiers

We have noticed these two identifiers in the above program. 

  • Value: Conventionally, we choose the name of the setter parameter as value, but we can choose a different name if we want. The value parameter contains the value that a property is assigned to. In the above program, we have initialized the property name as c.name = “GeeksforGeeks”, the value parameter contains the assigned value “GeeksforGeeks”.
  • Backing Field (field): It allows 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 the above program, the value is assigned to field, and then, field is assigned to get().

Private Modifier

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. Kotlin program to set the value by using a method inside a class.

Kotlin




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 company is: ${c.name}")
}

Output: 

Name of the company is: abc
Name of the new company 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 

Kotlin




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

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!