chanjungskim
03/20/2023, 8:36 AMJavier
03/20/2023, 8:52 AMchanjungskim
03/20/2023, 9:09 AMTom Hermann
03/21/2023, 12:17 AMpackage com.example
interface Bicycle {
fun changeCadence(newValue: Int)
fun changeGear(newValue: Int)
fun speedUp(increment: Int)
fun applyBrakes(decrement: Int)
}
Note that this interface simply defines what you can generally do with a bicycle, not how it is accomplished.
Classes can implement interfaces, so if you wanted to model a Peloton for example, you could start like this:
package com.example
class Peloton : Bicycle {
override fun changeCadence(newValue: Int) {
// perform change cadence
}
override fun changeGear(newValue: Int) {
// perform change gear
}
override fun speedUp(increment: Int) {
// perform speed up
}
override fun applyBrakes(decrement: Int) {
// perform slow down
}
}
In this example a Peloton is-a bicycle, since it implements the bicycle interface, so anywhere that wants a "bicycle" will accept a Peloton.
So lets say you have a "Rider" that can ride any old bicycle. Here is an example of creating a rider instance and having them ride a peloton.
package com.example
class Rider {
fun ride(bicycle: Bicycle) {
bicycle.changeGear(1)
bicycle.speedUp(11)
}
}
fun main() {
val peloton = Peloton()
Rider().ride(peloton)
}
So you can see that you could swap out different bike implementations (imagine a MountainBike
, BmxBike
, etc.)
and as long as it conforms to the contract you can have the rider ride it.
Once you fully understand classes / interfaces, Kotlin's site has a great write-up on sealed
interfaces and classes:
https://kotlinlang.org/docs/sealed-classes.html