Properties, Getters and Setters

Properties Have Accessors

In Kotlin you never write getName()/setName() by hand. Every property already has a getter (and a setter for var). You can customise them.

DeclarationGetterSetter
val name: Stringyesno
var name: Stringyesyes
var name: String + private setyes (public)only inside the class

Custom Getter (Computed Property)

Example

A custom getter is recalculated every time the property is read. No value is stored.

class Rectangle(val width: Int, val height: Int) {
    val area: Int
        get() = width * height

    val isSquare get() = width == height
}

fun main() {
    val r = Rectangle(4, 6)
    println("Area: ${r.area}")
    println("Square? ${r.isSquare}")
}

Output

Area: 24
Square? false

Custom Setter and the Backing Field

Inside an accessor, field refers to the stored value (the backing field). Writing age = value inside the setter would call the setter again forever, so always use field.

Example

class Profile {
    var age: Int = 0
        set(value) {
            field = if (value < 0) 0 else value
        }

    var username: String = ""
        set(value) {
            field = value.trim().lowercase()
        }
        get() = "@" + field
}

fun main() {
    val p = Profile()
    p.age = -5
    p.username = "  Abhinav_K  "
    println(p.age)
    println(p.username)
}

Output

0
@abhinav_k

Private Setter

Example

Allow everyone to read a value but only the class to change it.

class Counter {
    var count = 0
        private set

    fun increment() { count++ }
}

fun main() {
    val c = Counter()
    repeat(3) { c.increment() }
    println("Count = ${c.count}")
    // c.count = 10   // error: the setter is private
}

Output

Count = 3