🏎️ · Accessors

1 min read Β· Updated on by

A quick introduction to accessors (getters and setters) in Kotlin, default accessors, custom accessors, andΒ valΒ vs.Β varΒ in the context of properties.

When not specified, default getters and setters (i.e. return field and field = value) are automatically generated by the compiler. Kotlin also adds syntactic sugar that allows working with properties as if they were fields, so obj.x is actually obj.getX() and obj.x = y is actually obj.setX(y). It is important to remember that this is only syntactic sugar, and it is the accessor functions that actually get called.

If you need to customize the accessors, use get() and/or set():


class FullName(var firstName: String, var lastName: String) {
    var stringRepresentation: String
        // Accessors are just regular functions, so we can use either 
        // expression syntax or { } to define them
        get() = "First name is '$firstName', last name is '$lastName'"
        set(value) {
            // If no ' ' is found, assume whatever is passed 
            // in is lastName
            firstName = value.substringBefore(" ", "")
            lastName = value.substringAfter(" ")
        }
}


fun main() {
    val fullName = FullName("James", "Bond")

    // // prints "First name is 'James', last name is 'Bond'"
    println(fullName.stringRepresentation)

    fullName.stringRepresentation = "Ferdinand von Zeppelin"

    // prints "First name is 'Ferdinand', last name is 'von Zeppelin'"
    println(fullName.stringRepresentation)
}

Equipped with this knowledge, we can state the technical difference between properties defined usingΒ valΒ orΒ var:Β valΒ doesn't generate a setter, whileΒ varΒ does.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

The Kotlin Primer