Created
February 2, 2020 14:54
-
-
Save magdamiu/7f4790df22482b08359a5fb6f420e859 to your computer and use it in GitHub Desktop.
Delegation in Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
interface PetAction { | |
fun eat() | |
} | |
interface PetColor { | |
val color: String | |
} | |
object YellowColor : PetColor { | |
override val color = "yellow" | |
} | |
class PrintingPetAction(val food: String) : PetAction { | |
override fun eat() { | |
println(food) | |
} | |
} | |
class Cat(petColor: PetColor = YellowColor) : | |
PetAction by PrintingPetAction("eats a lot of fish"), | |
PetColor by petColor | |
fun delegate() { | |
val kittyCat = Cat() | |
println("Pet has color ${kittyCat.color}") | |
kittyCat.eat() | |
} | |
fun main(args: Array<String>) { | |
delegate() | |
} | |
// => Pet has color yellow | |
// => eats a lot of fish |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment