Menu
Coddy logo textTech

Recap - Zoo Keeper

Part of the Object Oriented Programming section of Coddy's Kotlin journey. Lesson 31 of 57.

challenge icon

Challenge

Medium

Plan a day at the zoo.

  • Animal(name, kg) is abstract with the abstract members species, food and dailyGrams(), and a method line() that returns Leo the lion: 5700 g meat.
  • Lion eats meat, 30 g per kg. Parrot eats seeds, 50 g a day whatever it weighs. Seal eats fish, 40 g per kg.
  • The interface Trainable has trick(). 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, or no show when 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

Practice on your own: Kotlin playground