Skip to content

Commit

Permalink
feat: Add code for chapter 10
Browse files Browse the repository at this point in the history
  • Loading branch information
dogriffiths committed Nov 29, 2018
1 parent c949cb4 commit bc0df78
Show file tree
Hide file tree
Showing 2 changed files with 100 additions and 0 deletions.
12 changes: 12 additions & 0 deletions chapter10/Generics/Generics.iml
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$">
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
</content>
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
<orderEntry type="library" name="KotlinJavaRuntime" level="project" />
</component>
</module>
88 changes: 88 additions & 0 deletions chapter10/Generics/src/Pets.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
abstract class Pet(var name: String)

class Cat(name: String) : Pet(name)

class Dog(name: String) : Pet(name)

class Fish(name: String) : Pet(name)

class Vet<T : Pet> {
fun treat(t: T) {
println("Treat Pet ${t.name}")
}
}

class Contest<T : Pet>(var vet: Vet<in T>) {
val scores: MutableMap<T, Int> = mutableMapOf()

fun addScore(t: T, score: Int = 0) {
if (score >= 0) scores.put(t, score)
}

fun getWinners(): MutableSet<T> {
val winners: MutableSet<T> = mutableSetOf()
val highScore = scores.values.max()
for ((t, score) in scores) {
if (score == highScore) winners.add(t)
}
return winners
}
}

interface Retailer<out T> {
fun sell(): T
}

class CatRetailer : Retailer<Cat> {
override fun sell(): Cat {
println("Sell Cat")
return Cat("")
}
}

class DogRetailer : Retailer<Dog> {
override fun sell(): Dog {
println("Sell Dog")
return Dog("")
}
}

class FishRetailer : Retailer<Fish> {
override fun sell(): Fish {
println("Sell Fish")
return Fish("")
}
}

fun main(args: Array<String>) {
val catFuzz = Cat("Fuzz Lightyear")
val catKatsu = Cat("Katsu")
val fishFinny = Fish("Finny McGraw")

val catVet = Vet<Cat>()
val fishVet = Vet<Fish>()
val petVet = Vet<Pet>()

catVet.treat(catFuzz)
petVet.treat(catKatsu)
petVet.treat(fishFinny)

val catContest = Contest<Cat>(catVet)
catContest.addScore(catFuzz, 50)
catContest.addScore(catKatsu, 45)
val topCat = catContest.getWinners().first()
println("Cat contest winner is ${topCat.name}")

val petContest = Contest<Pet>(petVet)
petContest.addScore(catFuzz, 50)
petContest.addScore(fishFinny, 56)
val topPet = petContest.getWinners().first()
println("Pet contest winner is ${topPet.name}")

val fishContest = Contest<Fish>(petVet)

val dogRetailer: Retailer<Dog> = DogRetailer()
val catRetailer: Retailer<Cat> = CatRetailer()
val petRetailer: Retailer<Pet> = CatRetailer()
petRetailer.sell()
}

0 comments on commit bc0df78

Please sign in to comment.