Skip to content
Tutorials Center
My learning

Topics

Lesson 61 of 134 ยท Classes and Objects

Delegated Properties: lazy, observable, vetoable, map

A complete guide to Kotlin delegated properties: how by works, lazy modes, observable, vetoable, notNull, map delegates, provideDelegate, property references and custom delegates.

A normal property stores a value and returns it. A delegated property hands both jobs to another object. You write val x: Int by something, and every read of x becomes a call to something.getValue(...), every write a call to something.setValue(...). That small idea gives you lazy values, change notifications, validation, map-backed objects and reusable behavior, all without repeating code in every class.

The Delegation lesson introduced by for interfaces and showed the first standard delegates. This lesson goes deeper into the property side: what the compiler really generates, every standard delegate and its options, how delegates can be shared between properties, how to write your own, and how to hook into their creation with provideDelegate. You should know properties, lambdas and operator conventions.

What the compiler does

For a property declared as var name: String by delegate, Kotlin generates a hidden field that holds the delegate, plus accessors that forward to it:

sequenceDiagram
    participant C as Calling code
    participant P as Property accessor (generated)
    participant D as Delegate object
    C->>P: user.name
    P->>D: getValue(user, nameProperty)
    D-->>P: "Ann"
    P-->>C: "Ann"
    C->>P: user.name = "Bo"
    P->>D: setValue(user, nameProperty, "Bo")

Reads and writes of a delegated property are plain calls to getValue and setValue on the delegate object.

The delegate needs these two operator functions (setValue only for var):

Kotlin
operator fun getValue(thisRef: Owner, property: KProperty<*>): T
operator fun setValue(thisRef: Owner, property: KProperty<*>, value: T)

thisRef is the object that owns the property (or null for top-level and local properties), and property describes the property being accessed; its name is available even without the reflection library. Because the delegate receives both, one delegate object can serve many properties in many classes.

The standard delegates in detail

lazy and its thread-safety modes

lazy computes the value on the first read and caches it. The overloaded versions choose a threading strategy:

Kotlin lazy: once only, and how to check whether it ran

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The three modes:

Mode Behavior Use when
SYNCHRONIZED (default) One thread computes; others wait Shared between threads
PUBLICATION Several threads may compute; the first result wins The computation is cheap and side-effect free
NONE No locking at all The value is only used from one thread

A lazy value never becomes stale: the block runs once, even if it returns null. If the block throws, the exception propagates and the next read tries again.

Delegates.observable and Delegates.vetoable

observable reports every assignment after it happened. vetoable is asked before and can refuse. Both receive the property, the old value and the new one:

Kotlin observable, vetoable and notNull side by side

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

notNull() is the delegate behind a property that cannot be initialized in the constructor but has a non-null type, for example one that a framework sets later. Reading it before assignment throws IllegalStateException. It also works for primitive types such as Int, where lateinit is not allowed. The next lesson, lateinit vs lazy, compares these options.

Storing properties in a map

A map can act as the delegate. The property name is the key. This is handy for objects built from JSON or configuration:

Kotlin Properties backed by a map

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

A missing key throws NoSuchElementException. The value is cast to the property's type when it is read, so a wrong type fails with a ClassCastException at that moment, not when you build the map. If you want defaults, wrap the map with withDefault { ... } and the delegate will call the default function for a missing key.

Delegating to another property

A property can hand its work to another property by using a property reference (::name). This is how you rename a property while keeping the old one working, or expose a private state under a second name:

Kotlin Delegating to another property

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

The same trick helps with deprecations: keep the old property as a delegate to the new one and mark it @Deprecated.

Writing your own delegate

Implement ReadOnlyProperty for a val, or ReadWriteProperty for a var. Both are tiny interfaces from kotlin.properties. You can also just write the operator functions without implementing anything:

Kotlin A reusable trimming delegate

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Each property has its own Trimmed object, because Trimmed() runs once per by expression and per instance of Form. That is why name and city do not overwrite each other.

A generic delegate works for any type. Here is one that logs reads and writes, used on a local variable. Local delegated properties are allowed too:

Kotlin A generic logging delegate on a local variable

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

provideDelegate: controlling delegate creation

Sometimes you want to check or register a property at the moment the class is built, not when it is first read. If the object after by has an operator provideDelegate, Kotlin calls it once per property, and its return value becomes the real delegate. This is how frameworks validate names or register properties:

Kotlin Validating a property at declaration time

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with readln()), it gets the next line from this box.

Both registrations print while Config() is being constructed, before any property is read. If you rename maxUsers to users, construction fails immediately with the message from require. Failing at construction beats failing at some later read.

Choosing the right tool

Need Use
Expensive value, computed once, maybe never by lazy
React to a change Delegates.observable
Reject invalid changes Delegates.vetoable (or a custom setter)
Non-null property assigned after construction lateinit or Delegates.notNull()
Object backed by a dynamic data source map delegate
Same behavior on many properties custom ReadWriteProperty
Rename a property by this::other

Two cautions. A delegate runs on every access, so keep getValue cheap. And delegated properties have no backing field, so you cannot write field inside an accessor of one; the state lives in the delegate.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which method does the compiler call when you read a property declared with by?

    A delegated property forwards reads to the delegate's operator getValue and, for a var, writes to setValue. Both receive the owner and a description of the property.
  2. 2. What happens if you read a property declared with Delegates.notNull() before assigning it?

    notNull() has no value until the first assignment. Reading too early throws IllegalStateException with a message that the property should be initialized before get.
  3. 3. How does a map-backed property find its value?

    The delegate looks up the property name as the key. A missing key throws NoSuchElementException for non-null properties.
  4. 4. When does provideDelegate run?

    provideDelegate is called while the object is being constructed, once per delegated property. Its result becomes the delegate, which makes it ideal for validation and registration.
  5. 5. Which LazyThreadSafetyMode is the default for lazy { }?

    SYNCHRONIZED is the default: the first thread computes the value while others wait. NONE avoids the cost when only one thread is involved.

Summary

  • val x by d turns reads into d.getValue(thisRef, property) and writes into d.setValue(...).
  • lazy runs its block once; choose the mode to match your threading, and use Lazy.isInitialized() to check.
  • observable notifies after a change, vetoable can refuse it, and notNull() guards late initialization.
  • A Map can back properties by name; missing keys throw NoSuchElementException.
  • by this::other or by ::topLevel redirects to another property.
  • Custom delegates implement ReadOnlyProperty or ReadWriteProperty; provideDelegate customizes how the delegate is created.

Next: lateinit vs lazy