From bc0df7836a627b032205086a80f0d1b299f963f8 Mon Sep 17 00:00:00 2001 From: David Griffiths Date: Thu, 29 Nov 2018 19:38:22 +0000 Subject: [PATCH] feat: Add code for chapter 10 --- chapter10/Generics/Generics.iml | 12 +++++ chapter10/Generics/src/Pets.kt | 88 +++++++++++++++++++++++++++++++++ 2 files changed, 100 insertions(+) create mode 100644 chapter10/Generics/Generics.iml create mode 100644 chapter10/Generics/src/Pets.kt diff --git a/chapter10/Generics/Generics.iml b/chapter10/Generics/Generics.iml new file mode 100644 index 0000000..245d342 --- /dev/null +++ b/chapter10/Generics/Generics.iml @@ -0,0 +1,12 @@ + + + + + + + + + + + + \ No newline at end of file diff --git a/chapter10/Generics/src/Pets.kt b/chapter10/Generics/src/Pets.kt new file mode 100644 index 0000000..cb7911f --- /dev/null +++ b/chapter10/Generics/src/Pets.kt @@ -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 { + fun treat(t: T) { + println("Treat Pet ${t.name}") + } +} + +class Contest(var vet: Vet) { + val scores: MutableMap = mutableMapOf() + + fun addScore(t: T, score: Int = 0) { + if (score >= 0) scores.put(t, score) + } + + fun getWinners(): MutableSet { + val winners: MutableSet = mutableSetOf() + val highScore = scores.values.max() + for ((t, score) in scores) { + if (score == highScore) winners.add(t) + } + return winners + } +} + +interface Retailer { + fun sell(): T +} + +class CatRetailer : Retailer { + override fun sell(): Cat { + println("Sell Cat") + return Cat("") + } +} + +class DogRetailer : Retailer { + override fun sell(): Dog { + println("Sell Dog") + return Dog("") + } +} + +class FishRetailer : Retailer { + override fun sell(): Fish { + println("Sell Fish") + return Fish("") + } +} + +fun main(args: Array) { + val catFuzz = Cat("Fuzz Lightyear") + val catKatsu = Cat("Katsu") + val fishFinny = Fish("Finny McGraw") + + val catVet = Vet() + val fishVet = Vet() + val petVet = Vet() + + catVet.treat(catFuzz) + petVet.treat(catKatsu) + petVet.treat(fishFinny) + + val catContest = Contest(catVet) + catContest.addScore(catFuzz, 50) + catContest.addScore(catKatsu, 45) + val topCat = catContest.getWinners().first() + println("Cat contest winner is ${topCat.name}") + + val petContest = Contest(petVet) + petContest.addScore(catFuzz, 50) + petContest.addScore(fishFinny, 56) + val topPet = petContest.getWinners().first() + println("Pet contest winner is ${topPet.name}") + + val fishContest = Contest(petVet) + + val dogRetailer: Retailer = DogRetailer() + val catRetailer: Retailer = CatRetailer() + val petRetailer: Retailer = CatRetailer() + petRetailer.sell() +} \ No newline at end of file