Class delegation

Let's rewrite the CalculatorMachine class in Kotlin:

class CalculatorMachine(private val delegate: Calculator): Calculator by delegate

That's it. Now you can use the CalculatorMachine class written in Kotlin similarly to the version written in Java:

fun main (args: Array<String>) {    CalculatorMachine(CalculatorBrain())}

You can see that the compiler generates the same bytecode for the Kotlin version of the CalculatorMachine class as for the Java version:

public final class delegation/kotlin/CalculatorMachine implements delegation/Calculator  {        private final Ldelegation/Calculator; delegate        public <init>(Ldelegation/Calculator;)V    @Lorg/jetbrains/annotations/NotNull;() // invisible, parameter 0    L0    ALOAD 1    LDC "delegate"    INVOKESTATIC ...

Get Mastering High Performance with Kotlin now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.