Skip to content

Instantly share code, notes, and snippets.

@magdamiu
Created February 2, 2020 14:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save magdamiu/7f4790df22482b08359a5fb6f420e859 to your computer and use it in GitHub Desktop.
Save magdamiu/7f4790df22482b08359a5fb6f420e859 to your computer and use it in GitHub Desktop.
Delegation in Kotlin
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