And that's that, moving on to android

This commit is contained in:
2020-03-05 17:15:37 -05:00
parent 01d373c5a7
commit ceed1df11f
9 changed files with 236 additions and 15 deletions

View File

@@ -0,0 +1,40 @@
package aquarium.generics
open class WaterSupply(var needsProcessed: Boolean)
class TapWater : WaterSupply(needsProcessed = true) {
fun addChemicalCleaners() {
needsProcessed = false
}
}
class FishStoreWater: WaterSupply(needsProcessed = false)
class LakeWater: WaterSupply(needsProcessed = true) {
fun filter() {
needsProcessed = false
}
}
interface Cleaner<in T: WaterSupply> {
fun clean(waterSupply: T)
}
class TapWaterCleaner: Cleaner<TapWater> {
override fun clean(waterSupply: TapWater) {
waterSupply.addChemicalCleaners()
}
}
class Aquarium<T: WaterSupply>(val waterSupply: T) {
fun addWater(cleaner: Cleaner<T>) {
if(waterSupply.needsProcessed) {
cleaner.clean(waterSupply)
}
println("adding water from $waterSupply")
}
inline fun <reified R: WaterSupply> hasWaterSupplyOfType() = waterSupply is R
}

View File

@@ -0,0 +1,20 @@
package aquarium.generics
fun main(args: Array<String>) {
genericExample()
}
fun genericExample() {
val cleaner = TapWaterCleaner()
val aquarium = Aquarium(TapWater())
isWaterClean(aquarium)
aquarium.addWater(cleaner)
}
inline fun <reified R: WaterSupply>Aquarium<*>.hasWaterSupplyOfType() = waterSupply is R
inline fun <reified T: WaterSupply>WaterSupply.isOfType() = this is T
fun <T: WaterSupply>isWaterClean(aquarium: Aquarium<T>) {
println("aquarium water is clean: ${aquarium.waterSupply.needsProcessed}")
}