Skip to content

Instantly share code, notes, and snippets.

@dzungvu
Created March 12, 2023 02:31
Show Gist options
  • Save dzungvu/84e9b4d1908e4da50223446c9b0b5139 to your computer and use it in GitHub Desktop.
Save dzungvu/84e9b4d1908e4da50223446c9b0b5139 to your computer and use it in GitHub Desktop.
//delegate
class DistanceCalculator() {
fun calculate(vihecle: Vihecle, time: Float): Float {
return vihecle.speed * time
}
}
abstract class Vihecle(open val speed: Float, val model: String) {
//use the delegate instead of override travel function in each subclass
val distanceCalculator = DistanceCalculator()
fun travel(time: Float) {
println("$model traveled ${distanceCalculator.calculate(this, time)}")
}
abstract fun drive()
}
class Car(override val speed: Float, model: String): Vihecle(speed, model) {
override fun drive() {
println("Driving a Car")
}
}
class Train(override val speed: Float, model: String): Vihecle(speed, model) {
override fun drive() {
println("Driving a Train")
}
}
fun main() {
val car = Car(60.0f, "Vinfast")
car.drive()
car.travel(15f)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment