Recap - Library Card
Part of the Object Oriented Programming section of Coddy's Kotlin journey. Lesson 6 of 57.
Challenge
MediumDeclare the class LibraryCard(val name: String, val limit: Int = 3). Its init block requires a non-blank name (name is empty) and a limit of at least 1 (limit must be positive). It keeps a list of borrowed titles. borrow(title) returns true and adds the title unless the card is at its limit or already holds it. giveBack(title) returns true when it removed the title. status() returns Ada: 2/3 (Dune, Emma) in borrowing order, or Ada: 0/3 when nothing is borrowed.
The supplied code reads the name, the limit (or an empty line for the default) and then commands +title or -title. It prints ok or no for each command and finally status(); an invalid card prints the error message instead.
Your code goes in LibraryCard.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()
try {
val card = if (input[1].isEmpty()) LibraryCard(input[0]) else LibraryCard(input[0], input[1].toInt())
for (cmd in input.drop(2)) {
val title = cmd.drop(1)
val done = if (cmd.startsWith("+")) card.borrow(title) else card.giveBack(title)
println(if (done) "ok" else "no")
}
println(card.status())
} catch (e: IllegalArgumentException) {
println(e.message)
}
}
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