Kotlin supports class delegation with the by keyword—forward interface implementations to a delegate object, reducing boilerplate versus manual forwarding in Java. Property delegation uses by lazy, by lazy(LazyThreadSafetyMode), and custom delegates.
Class delegation
interface Repository {
fun find(id: String): String
}
class CachedRepo(private val inner: Repository) : Repository by inner
The compiler generates forwarders for interface members you do not override.
Property delegation
val config by lazy { loadConfig() } computes once on first access—common for expensive initialization.
Important interview questions and answers
- Q: Class delegation vs inheritance?
A: Delegation composes behavior without subclassing the implementation—favor composition for decorators. - Q: lazy thread safety?
A: Defaultlazyis synchronized; useLazyThreadSafetyMode.NONEwhen single-threaded.
Self-check
- What keyword implements interface delegation?
- When does lazy initialize its value?
Tip: by lazy is thread-safe by default—pick LazyThreadSafetyMode when you know single-thread use.
Interview prep
- class delegation by?
Forwards interface to composed object—built-in pattern.
- lazy delegate?
Thread-safe lazy initialization on first access.