Skip to content

Kotlin basics : Custom Accessors

Devrath edited this page Dec 24, 2023 · 1 revision
  • We know that in kotlin classes we use properties to store the data. We use the constructors to set the data to the class.
  • Lot of the scenarios this works just fine with getter methods and setter methods or using the dot notation to access and modify the variable.
  • Below we can see the proper getter and setter methods
class Person(val firstName:String , val lastName:String){
    val fullName = "$firstName $lastName"
}
class DemoCustomAccessors {
    init { initiate() }
    private fun initiate() {
        var person = Person("Tony","Stark")
        println(person.fullName)
    }
}

OUTPUT:
Tony Stark

  • Now lets try with custom getter method unstead of dot operator and our implementation there with it - Note that we need to store the variable in var
  • This is currently a readonly way meaning the modified value is not set in the data class
class DemoCustomAccessors {
    init { initiate() }
    private fun initiate() {
        var person = Person("Tony","Stark")
        println(person.fullName)
    }
}

class Person(var firstName:String , var lastName:String){
    val fullName : String
        get() {
            firstName = "Johny"
            return "$firstName $lastName"
        }
}

OUTPUT:
Johny Stark

  • Now lets try with custom setter method unstead of dot operator and our implementation there with it
class DemoCustomAccessors {
    init { initiate() }
    private fun initiate() {
        var person = Person("Tony","Stark")
        println(person.fullName)
        person.firstName = "Frank"
        println(person.fullName)
    }
}

class Person(var firstName:String , var lastName:String){
    var fullName : String
        get() {
            // Custom implementation while getting value
            return "$firstName $lastName"
        }
        set(value) {
            // Custom implementation while setting value
            firstName = value
        }
}

OUTPUT:
Tony Stark
Frank Stark
Clone this wiki locally