Recap - Staff Directory
Part of the Object Oriented Programming section of Coddy's Kotlin journey. Lesson 21 of 57.
Challenge
MediumBuild a staff directory as a class hierarchy.
Person(name)is abstract. It declares the abstractrole()and implementscard(), which returnsAda (staff in sales)and cannot be overridden.Staff(name, department)is open; its role isstaff in sales.Manager(name, department)extendsStaffand keeps a private team.hire(member)returnstrueand adds the member when the member works in the same department, is not the manager and is not in the team yet, andfalseotherwise. Its role is theStaffrole followed by, 2 reports(usesuper).Contractor(name, days)extendsPerson; its role iscontractor 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
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 BooksPractice on your own: Kotlin playground