Kotlin - Getters & Setters

In this chapter we are going to learn about getters and setters. If you don't know about classes and object please read previous chapter.

In programming language getters is nothing but get the value of variable and setters is nothing but set the value of veriable

In kotlin getters and setters are optional, if we not creates getters and setters kotlin will auto creates.

Example of Getter & Setters

class Employee {
    var name: String = "Kotlin"

    // getter
    get() = field

    // setter
    set(value) {
        field = value
    }
}                          
                      

The above class is Equals to

class Employee {
    var name: String = "Kotlin"
}                          
                      

As we discussed if we not define the Getters and Setters Kotlin will auto creates these in the programm.


Example -2

fun main(args: Array) {
    val emp = Employee()
    emp.actualSal = 15000
    emp.sal = 35
    println("Chandu: actual Sal = ${emp.actualSal}")
    println("Chandu: pretended Sal = ${emp.sal}")
    val emp2 = Employee()
    emp2.actualSal = 18000
    emp2.sal = 35
    println("Indhu: actual Sal = ${emp2.actualSal}")
    println("Indhu: pretended sal = ${emp2.sal}")
}
class Employee {
    var sal: Int = 0
    get() = field
    set(value) {
        field = if (value < 18000)
            18000
        else if (value >= 18000 && value <= 30000)
            value
        else
            value-3000
    }
    var actualSal: Int = 0
}


Output
Chandu: actual Sal = 15000
Chandu: pretended Sal = 18000
Indhu: actual Sal = 18000
Indhu: pretended sal = 18000

Subscribe For Daily Updates