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](/learning-kotlin-introduction) * Koans used in here are [34](https://github.com/Kotlin/kotlin-koans/blob/master/src/iv_properties/n34DelegatesExamples.kt) and [35](https://github.com/Kotlin/kotlin-koans/blob/master/src/iv_properties/n35HowDelegatesWork.kt)

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
  3. class User {
  4.     var name : String by Delegate()
  5.     var eyeColour : String by Delegate();
  6. }
  8. class Delegate {
  9.     operator fun getValue(thisRef: Any?, property: KProperty<<em>>): String {
  10.         println("$thisRef, thank you for delegating '${property.name}' to me!")
  11.         return "HAHAHA"
  12.     }
  14.     operator fun setValue(thisRef: Any?, property: KProperty<</em>>, value: String) {
  15.         println("$value has been assigned to '${property.name}' in $thisRef.")
  16.     }
  17. }
  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. }