Books and Members
Part of the Object Oriented Programming section of Coddy's Kotlin journey. Lesson 50 of 57.
In this project you build the core of a library system. A Library class receives commands, one per line, and replies to each. Over five steps it learns to add books and members, lend and take back books, search the catalogue and print a report:
ADD_BOOK 1 Dune
JOIN ada
BORROW ada 1
RETURN ada 1
SEARCH dune
REPORTThe data model uses what this section taught. Book and Member each live in their own file. A book's borrower can be read everywhere but changes only through lendTo and giveBack, and a member exposes the ids of its loans as a read-only List. The library keeps both in private maps, so only its own methods can change them:
class Book(val id: Int, val title: String) {
var borrower: String? = null
private set
val isAvailable: Boolean
get() = borrower == null
fun lendTo(name: String) { borrower = name }
}Inside main:
val books = mutableMapOf<Int, Book>()
books[1] = Book(1, "Dune")
books.getValue(1).lendTo("ada")
println("${books.getValue(1).isAvailable} ${books.getValue(1).borrower}")Output:
false adahandle(line) splits the command and uses a when on its first word. Every branch returns its replies as a List<String>, so a command such as REPORT can reply with several lines, and an early return hands back a refusal. The title of a book may contain spaces, so it is everything after the id:
Inside main:
val p = "ADD_BOOK 7 The Hobbit".split(" ")
val id = p[1].toInt()
val title = p.drop(2).joinToString(" ")
println("$id: $title")Output:
7: The HobbitChallenge
EasyComplete Library.handle(line) for the first two commands:
ADD_BOOK <id> <title>: store a new available book and replyadded book 1: Dune; when the id is taken replybook 1 exists.JOIN <name>: add a member and replywelcome ada; when the name exists replyada is already a member.
The supplied code passes every input line to library.handle(line) and prints each returned reply on its own line. Member names are single lower-case words, book ids are whole numbers, and the input holds only the commands described so far. Any other command replies unknown command.
Your code goes in Book.kt, Member.kt and Library.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 library = Library()
for (line in input) {
for (reply in library.handle(line)) println(reply)
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
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