Kotlin Delegation: by lazy, observable and Class Delegation

Kotlin course · Advanced Kotlin · Lesson 46 of 51

Updated:

Delegation means handing a job to another object. Kotlin supports it directly with the by keyword, in two ways: delegated properties (a property’s get and set are handled by another object) and class delegation (a class forwards an interface’s functions to another object).

by lazy: compute a value on first use

A lazy property runs its block only the first time it’s read, then remembers the result:

class Report {
    val data: List<Int> by lazy {
        println("Loading data…")      // runs only once
        listOf(4, 8, 15, 16, 23, 42)
    }
}

fun main() {
    val r = Report()
    println("Report created")
    println(r.data.sum())
    println(r.data.size)              // no second "Loading data…"
}

Output:

Report created
Loading data…
108
6

lazy is perfect for expensive objects you might not need, such as a database, a large parser or a formatter. It’s thread-safe by default.

lateinit varval … by lazy
Who sets the valueyour code, laterthe lazy block, on first read
Can change lateryesno
Typesnon-null, not primitivesany
Typical useviews, injected dependenciesexpensive, computed values

Delegates.observable: react to changes

import kotlin.properties.Delegates

class Settings {
    var theme: String by Delegates.observable("light") { _, old, new ->
        println("Theme changed from $old to $new")
    }
}

fun main() {
    val s = Settings()
    s.theme = "dark"
    s.theme = "system"
    println("Current: ${s.theme}")
}

Output:

Theme changed from light to dark
Theme changed from dark to system
Current: system

Delegates.vetoable: reject invalid values

import kotlin.properties.Delegates

class Volume {
    var level: Int by Delegates.vetoable(50) { _, _, new -> new in 0..100 }
}

fun main() {
    val v = Volume()
    v.level = 80
    println(v.level)
    v.level = 150        // rejected: stays 80
    println(v.level)
}

Output:

80
80

Storing properties in a map

class User(map: Map<String, Any?>) {
    val name: String by map
    val age: Int by map
}

fun main() {
    val u = User(mapOf("name" to "Kabir", "age" to 31))
    println("${u.name} is ${u.age}")
}

Output:

Kabir is 31

This is handy when data arrives as a map, for example from JSON or a config file. Use MutableMap with var properties to write back to the map.

Writing your own property delegate

A delegate is any object with getValue (and setValue for var). Here’s one that trims and limits text:

import kotlin.reflect.KProperty

class Trimmed(private val maxLength: Int) {
    private var value = ""
    operator fun getValue(thisRef: Any?, property: KProperty<*>) = value
    operator fun setValue(thisRef: Any?, property: KProperty<*>, newValue: String) {
        value = newValue.trim().take(maxLength)
    }
}

class Profile {
    var username: String by Trimmed(10)
    var bio: String by Trimmed(30)
}

fun main() {
    val p = Profile()
    p.username = "   meera_the_developer   "
    p.bio = "  Android dev who loves Kotlin and Jetpack Compose  "
    println("[${p.username}]")
    println("[${p.bio}]")
}

Output:

[meera_the_]
[Android dev who loves Kotlin a]

Class delegation: implement an interface with by

Instead of writing every function of an interface yourself, you can forward them to an object that already implements it, and override only what you need:

interface Logger {
    fun info(msg: String)
    fun error(msg: String)
}

class ConsoleLogger : Logger {
    override fun info(msg: String) = println("INFO: $msg")
    override fun error(msg: String) = println("ERROR: $msg")
}

class TimestampLogger(private val inner: Logger) : Logger by inner {
    override fun error(msg: String) = inner.error("[12:00] $msg")   // only change error()
}

fun main() {
    val log = TimestampLogger(ConsoleLogger())
    log.info("App started")
    log.error("Network timeout")
}

Output:

INFO: App started
ERROR: [12:00] Network timeout

This is the decorator pattern, and it’s often a better choice than inheritance (“favor composition over inheritance”).

Delegation you’ll see in Android

// Activity / Fragment
private val viewModel: MainViewModel by viewModels()

// Jetpack Compose
var count by remember { mutableStateOf(0) }

Both are delegated properties. by viewModels() creates or reuses the ViewModel, and by remember { mutableStateOf(…) } makes the screen redraw when count changes.

Common mistakes

  • Using lazy on a var: lazy only works with val.
  • Heavy work in lazy on the main thread: it still runs on whichever thread reads it first.
  • Forgetting the imports: Delegates needs import kotlin.properties.Delegates, and Compose’s by with state needs getValue/setValue imports (Android Studio adds them).

Exercise

Create a Cart whose total is calculated lazily, whose coupon change is logged with observable, and whose quantity can never go below 1.

import kotlin.properties.Delegates

class Cart(private val prices: List<Int>) {
    val total: Int by lazy {
        println("(calculating total)")
        prices.sum()
    }
    var coupon: String? by Delegates.observable(null) { _, old, new -> println("Coupon: $old -> $new") }
    var quantity: Int by Delegates.vetoable(1) { _, _, new -> new >= 1 }
}

fun main() {
    val cart = Cart(listOf(499, 1299, 199))
    println(cart.total)
    println(cart.total)
    cart.coupon = "NEW10"
    cart.quantity = 0
    cart.quantity = 3
    println("Quantity: ${cart.quantity}")
}

Output:

(calculating total)
1997
1997
Coupon: null -> NEW10
Quantity: 3

FAQ

What does by lazy do in Kotlin?

It creates a read-only property whose value is computed the first time you read it, then cached.

What is the difference between lateinit and lazy?

lateinit var is a mutable property you assign yourself later. val … by lazy is computed automatically on first use and can’t change.

What is class delegation in Kotlin?

Writing class A(b: B) : Interface by b, so A forwards the interface’s functions to b and can override only the ones it wants to change.

WhatsApp us📞 Call now