Recap - Zoo Keeper
Part of the Object Oriented Programming section of Coddy's Kotlin journey. Lesson 31 of 57.
Challenge
MediumPlan a day at the zoo.
Animal(name, kg)is abstract with the abstract membersspecies,foodanddailyGrams(), and a methodline()that returnsLeo the lion: 5700 g meat.Lioneats meat, 30 g per kg.Parroteats seeds, 50 g a day whatever it weighs.Sealeats fish, 40 g per kg.- The interface
Trainablehastrick(). Parrots (Polly says hello) and seals (Sammy balances a ball) are trainable; lions are not. - The extension
List<Animal>.foodTotals()returns the grams per food, with the foods in alphabetical order:fish 4000, meat 5700. showLineup(animals)returns the tricks of the trainable animals in order, using a type check, orno showwhen there are none.
The supplied code reads lines lion,Leo,190, parrot,Polly,1 or seal,Sammy,100 and prints every line(), then food: with the totals and one show: line per returned trick.
Your code goes in Animal.kt, Trainable.kt, Lion.kt, Parrot.kt, Seal.kt and Functions.kt. Main.kt holds the supplied input/output code and cannot be edited.
Try it yourself
fun main() {
// Supplied input/output code: keep it as it is
val input = generateSequence(::readLine).toList()
val animals = input.map { line ->
val (kind, name, kg) = line.split(",")
when (kind) {
"lion" -> Lion(name, kg.toInt())
"parrot" -> Parrot(name, kg.toInt())
else -> Seal(name, kg.toInt())
}
}
for (a in animals) println(a.line())
println("food: " + animals.foodTotals())
for (s in showLineup(animals)) println("show: $s")
}
All lessons in Object Oriented Programming
1Classes and Objects
Working With FilesDefining ClassesPrimary Constructorsinit Blocks and ValidationSecondary ConstructorsRecap - Library Card4Inheritance
Open Classes and SubclassesOverriding Memberssuper and ConstructorsAbstract ClassesRecap - Staff Directory2Properties and Encapsulation
Custom AccessorsVisibility ModifiersPrivate Setterslazy and lateinitRecap - Bank Account5Interfaces
Declaring InterfacesDefault MethodsMultiple InterfacesInterfaces as TypesRecap - Payment Methods8Generics
Generic FunctionsGeneric ClassesType ConstraintsVariance With in and outRecap - Priority Queue11Project: Library Management
Books and MembersBorrowing Books3Objects and Companions
Object DeclarationsCompanion ObjectsConstants With constObject ExpressionsRecap - Ticket Office6Polymorphism
Dynamic DispatchType Checks and Smart Castswhen With TypesExtension FunctionsRecap - Zoo KeeperPractice on your own: Kotlin playground