Kotlin
Checking out
Write the checkout flow with checkout and return functions.
Checking out
For checkout the library must track which book is held by which member. Use val borrowed = mutableMapOf<String, String>(): the key is the book number isbn and the value is the member number memberId.
The fun checkout(memberId: String, isbn: String) method adds a record with borrowed[isbn] = memberId. The fun returnBook(isbn: String) method removes the record with borrowed.remove(isbn). This way a book can be held by only one member at a time; when returned the record is cleared and the book becomes available again.
checkout and returnBook
The checkout method lends the book to a member: fun checkout(memberId: String, isbn: String) { borrowed[isbn] = memberId; println("Checkout: $memberId -> $isbn") }.
The returnBook method takes the book back: fun returnBook(isbn: String) { borrowed.remove(isbn); println("Return: $isbn") }. The output reports the action to the console. These two methods are added to the Library class and called from main as lib.checkout("M1", "978-1").
Exercise Add checkout and returnBook
Add val borrowed = mutableMapOf<String, String>() to the Library class. Write fun checkout(memberId: String, isbn: String) with borrowed[isbn] = memberId and println("Checkout: $memberId -> $isbn"). Write fun returnBook(isbn: String) with borrowed.remove(isbn) and println("Return: $isbn"). In main call checkout("M1", "978-1") then returnBook("978-1").
Show example solution
data class Book(val title: String, val author: String, val isbn: String)
data class Member(val name: String, val id: String)
class Library {
val books = mutableListOf<Book>()
val members = mutableListOf<Member>()
val borrowed = mutableMapOf<String, String>()
fun addBook(book: Book) { books.add(book) }
fun addMember(member: Member) { members.add(member) }
fun checkout(memberId: String, isbn: String) {
borrowed[isbn] = memberId
println("Checkout: $memberId -> $isbn")
}
fun returnBook(isbn: String) {
borrowed.remove(isbn)
println("Return: $isbn")
}
}
fun main() {
val lib = Library()
lib.addBook(Book("War and Peace", "Tolstoy", "978-1"))
lib.addMember(Member("Alex", "M1"))
lib.checkout("M1", "978-1")
lib.returnBook("978-1")
}
Test yourself
-
What does borrowed.remove(isbn) do?
- Removes the checkout record
- Checks out the book
- Adds a new member
- Prints the list
Show answer
Removes the checkout record — The remove method deletes the key from the map, returning the book.
-
Match the checkout concepts
- borrowed[isbn]
- Checkout record
- borrowed.remove(isbn)
- Return
- memberId
- Member
- isbn
- Book
-
Complete the returnBook method
fun returnBook(isbn: String) {
borrowed.____(isbn)
}
Show answer
fun returnBook(isbn: String) {
borrowed.remove(isbn)
}
Next lesson: Search and filter