Created
October 2, 2019 10:57
-
-
Save wojciech-zurek/72134d2f5ebe98de98cf8bdceafe0568 to your computer and use it in GitHub Desktop.
Example of Delegation with overriding 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
fun main() { | |
val car = Car("red", 200) | |
val derived = Derived(car) | |
println(derived.getColor())//red plus black | |
println(derived.getMaxSpeed())//200 | |
} | |
interface Vehicle { | |
fun getColor(): String | |
fun getMaxSpeed(): Int | |
} | |
data class Car(private val color: String, private val maxSpeed: Int) : Vehicle { | |
override fun getColor() = color | |
override fun getMaxSpeed() = maxSpeed | |
} | |
class Derived(vehicle: Vehicle) : Vehicle by vehicle { | |
private val c = vehicle.getColor() | |
override fun getColor() = "$c plus black" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment