Skip to content

Instantly share code, notes, and snippets.

@wojciech-zurek
Created October 2, 2019 10:57
Show Gist options
  • Save wojciech-zurek/72134d2f5ebe98de98cf8bdceafe0568 to your computer and use it in GitHub Desktop.
Save wojciech-zurek/72134d2f5ebe98de98cf8bdceafe0568 to your computer and use it in GitHub Desktop.
Example of Delegation with overriding in Kotlin
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