Skip to content
ArceApps Logo ArceApps
ES

Kotlin Delegation: Clean Code Pattern

2 min read
Kotlin Delegation: Clean Code Pattern

🤝 Composition over Inheritance

Inheritance is often abused in OOP. It creates tight coupling. The Delegation pattern solves this by favoring composition. Kotlin makes this a first-class citizen with the by keyword.

The Problem

You want to extend the functionality of a class (e.g., ArrayList), but you can’t or shouldn’t inherit from it directly because you only need to override one method and delegate the rest.

The Solution: Class Delegation

interface Base {
    fun print()
}

class BaseImpl(val x: Int) : Base {
    override fun print() { print(x) }
}

class Derived(b: Base) : Base by b

fun main() {
    val b = BaseImpl(10)
    Derived(b).print() // prints 10
}

The compiler generates all the forwarding methods for Base interface automatically. Zero boilerplate.

📦 Property Delegation

The most common use case in Android.

by lazy

Delays initialization until the first access. Thread-safe by default.

val heavyObject: Heavy by lazy {
    Heavy() // Computed only once
}

by viewModels()

In Android KTX, we delegate ViewModel creation to a factory.

val viewModel: UserViewModel by viewModels()

by remember (Compose)

Not technically a property delegate in the language sense, but conceptually similar. It delegates state retention to the composition.

🛠️ Custom Delegates

You can write your own!

class SharedPrefDelegate(context: Context, key: String, default: String) {
    // operator getValue / setValue
}

var username by SharedPrefDelegate(context, "user_name", "Guest")

Now, username = "Alex" writes to SharedPreferences automatically.

⚠️ When NOT to Use It

  • Performance: While negligible, there is a tiny overhead for property delegation (object allocation).
  • Readability: Don’t hide complex logic in custom delegates. If a variable assignment triggers a network call, it’s confusing.

🏁 Conclusion

Delegation is a powerful tool to reduce boilerplate and enforce separation of concerns. Use standard delegates (lazy, observable) freely, but be cautious with custom ones.

Share this post:
SOLID Principles: Android Examples
SOLID June 21, 2025

SOLID Principles: Android Examples

Understanding SOLID principles in modern Android. Examples using Kotlin, Hilt, and MVVM.

Read more
A2UI 1.0: Native Agent UI on Android
AI November 19, 2026

A2UI 1.0: Native Agent UI on Android

A2UI lets AI agents generate native Compose UI instead of text. Learn the protocol, renderer, and build your first agent-driven screen.

Read more
ODD for Android: Kotlin tests and a practical lab
ODD October 30, 2026

ODD for Android: Kotlin tests and a practical lab

Apply ODD to a fictional Android app: build a Kotlin streak reducer, run five JVM checks and plan honest Room and Compose verification without fake results.

Read more