Kotlin- Properties, Getters, Setters

Kotlin- Properties, Getters, Setters

Introduction

Kotlin properties are variables that are declared inside the class but outside the method.

It can be declared either as mutable using the var' keyword or read-only using the val keyword.

Full syntax for declaring a property:

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

The initializer, getter and setter are optional. Property type is optional if it can be inferred from the initializer.

Examples of properties

var name: String = "Mike" 
var name = "Mike" // type is inferred as String, hence omitted
var name = "John" // var can be re-assigned

val name = "Mike"
val name = "John" // It cannot be re-assigned

By default, properties in Kotlin are public and final. For private and protected you need to add it explicitly.

Getters and Setters (Accessors)

As the name suggests, getters are used for getting value of the property. Similarly, setters are used for setting value of the property.

In Kotlin, getters and setters are optional and are auto-generated if you do not create them.

Auto-generated Accessors

class Country {
var currency: String = "dollar"
}

The above code is equivalent to

class Country {
    var currency: String = "dollar"

    get() = field       // getter

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

Since, we do not modify accessors here, so we can omit it and use it like

class Country {
var currency: String = "dollar"
}

fun main() {
val c= Country()
c.currency = "rupee"  // access setter
println("${c.currency}") // access getter
}

Field and Value Identifiers

  1. 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 initialized the property name as c.currency = “dollar”, the value parameter contains the assigned value “dollar”.

  1. 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().

Custom Accessors

We can override auto-generated accessors

class Country {
    var currency: String = "dollar"

    get() {  // custom getter 
           return field.toLowerCase() 
        } 

    set(value) {  // custom setter
        field = if(value = "dollar" ) value else throw IllegalArgumentException("Currency must be dollar") 
    }
}

Did you find this article valuable?

Support Md Nehaluddin Haider by becoming a sponsor. Any amount is appreciated!