Recapping Property Custom Accessors

As we saw in the preceding chapter, you can override the getter and/or setter for a regular property:

val stuff = mapOf("something" to "This is the 'something' value")
val something: String?
  get() = stuff["something"]

fun main() {
  println(something)
}
val stuff = mutableMapOf<String, String?>("something" to "This is the 'something' value")
var something: String?
  get() = stuff["something"]
  set(value) { stuff["something"] = value }

fun main() {
  something = "This is different"
  println(something)
}

These allow you to tailor the use of the property, to the point where you might not actually use the backing field of the property at all.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.