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 kotlin/jvm/internal/Intrinsics.checkParameterIsNotNull (Ljava/lang/Object;Ljava/lang/String;)V L1 LINENUMBER 6 L1 ALOAD 0 INVOKESPECIAL java/lang/Object.<init> ()V ALOAD 0 ALOAD 1 PUTFIELD...