Delegation Flashcards

KOTLIN › Types & Classes

What does class Derived(b: Base) : Base by b do?
It implements interface Base by delegating all of Base's members to the object b. The compiler generates forwarding methods, so Derived needs no manual implementations. This is composition over inheritance.
If you override a member in the deriving class, can the delegate object's methods see that override?
No. The delegate only knows its own implementation. If b.print() reads b's message, an overridden message in Derived is invisible to it; b.print() still uses b's own value.
What operator functions must a custom property delegate provide?
getValue(thisRef, property: KProperty<*>) for a val; var also requires setValue(thisRef, property: KProperty<*>, value). Both must be marked operator and can be member or extension functions.
What is by lazy { ... } and when is the lambda run?
lazy returns a Lazy<T> delegate that computes the value on first access and caches it; later reads return the cached value. It works only on val. The lambda runs once, lazily.
What are the three LazyThreadSafetyMode options?
SYNCHRONIZED (default; locks so only one thread initializes), PUBLICATION (multiple threads may compute, first result wins), and NONE (no synchronization, fastest, single-thread use only).
Difference between Delegates.observable and Delegates.vetoable?
observable's handler fires after the assignment (old, new) for notification. vetoable's handler fires before and returns a Boolean; returning false rejects the change and keeps the old value.
How does map-backed delegation work?
val name: String by map reads map["name"]. A read-only Map gives val properties; a MutableMap supports var (setValue writes back). Common for parsing JSON-like dynamic data.
What do ReadOnlyProperty and ReadWriteProperty provide?
Standard library interfaces with the getValue (and setValue for ReadWrite) signatures, so you implement a delegate without writing operator funs by hand. ReadWriteProperty extends ReadOnlyProperty.
What is provideDelegate used for?
An operator fun provideDelegate(thisRef, property) called when the delegate is created, letting you validate or customize the delegate at binding (declaration) time instead of at first access.

Back to Delegation