You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
overridefunmakeSound() =println("I'm The King of Rock 'N' Roll: $n") // 2
18
+
}
19
+
20
+
// Tom Araya is the "singer" of Slayer
21
+
classTomAraya(n:String): SoundBehaviour by ScreamBehavior(n) // 3
22
+
23
+
// You should know ;)
24
+
classElvisPresley(n:String): SoundBehaviour by RockAndRollBehavior(n) // 3
25
+
26
+
funmain(args:Array<String>) {
27
+
val tomAraya =TomAraya("Trash Metal!")
28
+
tomAraya.makeSound() // 4
29
+
val elvisPresley =ElvisPresley("Dancin' to the Jailhouse Rock.")
30
+
elvisPresley.makeSound()
31
+
}
32
+
```
33
+
34
+
</div>
35
+
36
+
In Kotlin it's easy to delegate method calls without any boilersplate.
37
+
38
+
1. The interface SoundBehaviour is defined. Later there will be one class that implements the method and another will also have the interface, but just delegates the method call.
39
+
2. The class ScreamBehavior and RockAndRollBehavior actually implement the method.
40
+
3. The class TomAraya and ElvisPresley just delegate the methods defined by the interface SoundBehaviour to the responsible implementation. But doesn't need any boilerplate to delegate the method call at all.
41
+
4. Call makeSound() on tomAraya of type TomAraya or elvisPresley of type ElvisPresley and it is delegated to the assiciated class
0 commit comments