Menu
Coddy logo textTech

Recap - Staff Directory

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

challenge icon

Challenge

Medium

Build a staff directory as a class hierarchy.

  • Person(name) is abstract. It declares the abstract role() and implements card(), which returns Ada (staff in sales) and cannot be overridden.
  • Staff(name, department) is open; its role is staff in sales.
  • Manager(name, department) extends Staff and keeps a private team. hire(member) returns true and adds the member when the member works in the same department, is not the manager and is not in the team yet, and false otherwise. Its role is the Staff role followed by , 2 reports (use super).
  • Contractor(name, days) extends Person; its role is contractor for 30 days.

The supplied code reads commands staff Ada sales, manager Bo sales, contractor Cy 30 or hire Bo Ada (it prints hired or refused, also when a name is unknown), then prints every person's card in the order they were added.

Your code goes in Person.kt, Staff.kt, Manager.kt and Contractor.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 people = mutableListOf<Person>()
    val staff = mutableMapOf<String, Staff>()
    val managers = mutableMapOf<String, Manager>()
    for (cmd in input) {
        val p = cmd.split(" ")
        when (p[0]) {
            "staff" -> Staff(p[1], p[2]).also { people.add(it); staff[it.name] = it }
            "manager" -> Manager(p[1], p[2]).also { people.add(it); staff[it.name] = it; managers[it.name] = it }
            "contractor" -> people.add(Contractor(p[1], p[2].toInt()))
            "hire" -> {
                val boss = managers[p[1]]
                val worker = staff[p[2]]
                println(if (boss != null && worker != null && boss.hire(worker)) "hired" else "refused")
            }
        }
    }
    for (person in people) println(person.card())
}

All lessons in Object Oriented Programming

Practice on your own: Kotlin playground