Kotlin Idioms Delegate to a class without providing it in the public constructor


Assume you want to delegate to a class but you do not want to provide the delegated-to class in the constructor parameter. Instead, you want to construct it privately, making the constructor caller unaware of it. At first this might seem impossible because class delegation allows to delegate only to constructor parameters. However, there is a way to do it, as given in this answer:

class MyTable private constructor(table: Table<Int, Int, Int>) : Table<Int, Int, Int> by table {

    constructor() : this(TreeBasedTable.create()) // or a different type of table if desired


With this, you can just call the constructor of MyTable like that: MyTable(). The Table<Int, Int, Int> to which MyTable delegates will be created privately. Constructor caller knows nothing about it.

This example is based on this SO question.