Kotlin support implementation delegation allowing you to eliminate boilerplate code.
class Container<K,E>(val map: Map<K,E> = TreeMap()) : Map<K,E> by map {
//other stuff, new methods etc
}
All the methods of the Map interface are delegate to the val map (methods of Map can still be selectively overriden).
However the following is not allowed:
class Container<K,E>() : Map<K,E> by map {
val map: Map<K,E> = TreeMap()
//other stuff, new methods etc
}
Any plans to support implementation delegation using vals (final variables)?
We have pretty old issue about it: KT-2747. Now the semantic of delegation is the following: expression to delegate (after "by") is computed after calling superconstructor, but before other class initialization (everything in class body, including vals). It is saved in class state and never computed again.
We may allow delegation to some expression which would be executed on each delegated call (and support your case), but we haven’t decided it yet. Probably, we’ll need to decide it before Kotlin 1.0.