Delegation Interview Questions

KOTLIN › Types & Classes

What is class delegation with the 'by' keyword, and why is it described as composition over inheritance?

What a strong answer covers: class LoggingList<T>(private val inner: MutableList<T>) : MutableList<T> by inner generates forwarding methods to inner for every interface member, so you only override what you want to change. You get decorator behaviour without inheriting an implementation class, avoiding the fragile base class problem, and you can delegate to any implementation of the interface.

What are delegated properties? Give examples of standard delegates and one you might write yourself.

What a strong answer covers: val x by delegate routes the getter (and setter) through getValue/setValue on a delegate object. Standard ones: lazy, Delegates.observable, Delegates.vetoable, notNull, and delegating to a Map. On Android: by viewModels(), by navArgs(), by remember in Compose, and custom ones like a SharedPreferences-backed property or a Fragment argument delegate.

How does 'by viewModels()' work under the hood?

What a strong answer covers: It's a property delegate returning a Lazy<VM>: on first access it gets the ViewModelStore from the owner (Activity or Fragment) and a factory (Hilt's if present), and asks ViewModelProvider for the instance, creating it only if the store doesn't already hold one. So the same ViewModel survives configuration changes because the store survives them, not the property.

What are the pitfalls of class delegation, for example when the delegate calls its own methods?

What a strong answer covers: The delegate doesn't know about your overrides: if inner.addAll internally calls add, your overridden add isn't called because the delegate calls its own. Delegation is also fixed at construction: the delegate reference is captured once. And the wrapper and delegate have separate identities, which matters for equals. A strong answer contrasts this with inheritance, where self-calls dispatch to overrides.

Write, or describe, a property delegate that persists a value to SharedPreferences or DataStore. What threading and lifecycle issues do you need to handle?

What a strong answer covers: Implement ReadWriteProperty<Any?, T> whose getValue reads prefs.getX(key, default) and setValue writes with edit { putX }, often using property.name as the key, plus provideDelegate to validate at declaration. Issues: SharedPreferences reads can block on first load (disk I/O on main thread), apply is async while commit blocks, DataStore is suspend-only so a synchronous delegate doesn't fit it well, and you need a way to observe changes, so exposing a Flow is often better than a delegate.

Back to Delegation