Skip to main content
**More Information**
  • This is the 25th post in a multipart series.
    If you want to read more, see our series index
  • Koans used in here are 34 and 35

The fourth set of Koans looks at properties and the first two look at getters and setters. If you coming from another programming language then these should work the way you expect they should. This post will look at the amazing by keyword in the third and fourth examples. The by keyword enables us to delegate the getter/setter to be handled by a separate class which means that common patterns can be extracted and reused.

Out of the box, there are five built-in options which I will expand into in their own posts, but for now, let us build our own delegate class. In this example, we can assign any value but the result we get is always HAHAHA. We could store the result in the instance and return the value assigned but we do not have to. The key take away is that we have ensured the logic for our properties in one reusable place, rather than scattered across multiple getters and setters.

import kotlin.reflect.KProperty

class User {
    var name : String by Delegate()
    var eyeColour : String by Delegate();
}

class Delegate {
    operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
        println("$thisRef, thank you for delegating '${property.name}' to me!")
        return "HAHAHA"
    }
 
    operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
        println("$value has been assigned to '${property.name}' in $thisRef.")
    }
}

fun main(args: Array<String>) {
    val user = User()
    user.name = "Robert"
    user.eyeColour = "Green"
    println("My word ${user.name} but your eyes are ${user.eyeColour}")
}