And that's that, moving on to android
This commit is contained in:
40
src/aquarium/generics/Aquarium.kt
Normal file
40
src/aquarium/generics/Aquarium.kt
Normal 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
|
||||
}
|
||||
|
||||
|
||||
20
src/aquarium/generics/main.kt
Normal file
20
src/aquarium/generics/main.kt
Normal 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}")
|
||||
}
|
||||
Reference in New Issue
Block a user