Delegation
Delegation is an extremely powerful feature of Kotlin. This section sums up several approaches that can improve the performance of your application.
Singleton delegate object
If you use equals
objects as delegates several times, you can convert a delegate class to an object:
object CalculatorBrain: Calculator { override fun performOperation(operand: String): Int = TODO() }
Then, you can use an instance of this class as a delegate object:
class CalculatorMachine(): Calculator by CalculatorBrain
Now, you don't need to create a new instance of the delegate object all the time and pass it to a constructor. You can also use a similar approach with delegated properties:
object SingletonDelegate : ReadOnlyProperty<Any?, String?> { override fun getValue(thisRef: Any?, property: KProperty<*>): String? { return property.name } }
We can use SingletonDelegate
as follows:
class Main { val property by SingletonDelegate val another by SingletonDelegate }