Learning Kotlin: by

Submitted by Robert MacLean on Mon, 08/27/2018 - 09:00

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.

  1. import kotlin.reflect.KProperty
  2.  
  3. class User {
  4.     var name : String by Delegate()
  5.     var eyeColour : String by Delegate();
  6. }
  7.  
  8. class Delegate {
  9.     operator fun getValue(thisRef: Any?, property: KProperty<*>): String {
  10.         println("$thisRef, thank you for delegating '${property.name}' to me!")
  11.         return "HAHAHA"
  12.     }
  13.  
  14.     operator fun setValue(thisRef: Any?, property: KProperty<*>, value: String) {
  15.         println("$value has been assigned to '${property.name}' in $thisRef.")
  16.     }
  17. }
  18.  
  19. fun main(args: Array<String>) {
  20.     val user = User()
  21.     user.name = "Robert"
  22.     user.eyeColour = "Green"
  23.     println("My word ${user.name} but your eyes are ${user.eyeColour}")
  24. }