TExcelTAD
Home › Kotlin › Kotlin Mini Project

Kotlin Mini Project: Library Manager

In this project you'll build a small library manager step by step: books and members, borrowing and returning, fees for late returns, and a report. Each step is a complete, runnable program that grows from the previous one, using the features you've learned: data classes, enums, sealed results, collections, null safety, extension functions and scope functions.

Step New idea
1 model the data with data classes and an enum
2 a Library class with private mutable state
3 borrowing with a sealed Result type
4 returns, due dates and late fees
5 reports with collection operations

Days are plain integers ("day 0, day 1, …") to keep the output deterministic. A real app would use kotlinx-datetime or java.time.LocalDate.

Step 1: The data model

Start with the nouns of the problem. A Book has an id, title, author and genre; a Member has an id and a name. Data classes give us toString, equals and copy for free.

kotlin · try it yourself
enum class Genre { FICTION, SCIENCE, HISTORY, KIDS }

data class Book(val id: Int, val title: String, val author: String, val genre: Genre)
data class Member(val id: Int, val name: String)

fun main() {
    val books = listOf(
        Book(1, "Dune", "Frank Herbert", Genre.FICTION),
        Book(2, "Cosmos", "Carl Sagan", Genre.SCIENCE),
        Book(3, "SPQR", "Mary Beard", Genre.HISTORY)
    )
    val ana = Member(1, "Ana")

    books.forEach { println(it) }
    println(ana)
    println(books.groupBy { it.genre }.keys)
}
Book(id=1, title=Dune, author=Frank Herbert, genre=FICTION)
Book(id=2, title=Cosmos, author=Carl Sagan, genre=SCIENCE)
Book(id=3, title=SPQR, author=Mary Beard, genre=HISTORY)
Member(id=1, name=Ana)
[FICTION, SCIENCE, HISTORY]

Step 2: The Library class

The library owns the catalogue. Its collections are private and mutable; the outside world only sees read-only views. findBook returns Book? — a missing book is a normal situation, not an exception.

kotlin · try it yourself
enum class Genre { FICTION, SCIENCE, HISTORY, KIDS }
data class Book(val id: Int, val title: String, val author: String, val genre: Genre)
data class Member(val id: Int, val name: String)

class Library {
    private val books = mutableMapOf<Int, Book>()
    private val members = mutableMapOf<Int, Member>()

    val catalogue: List<Book> get() = books.values.sortedBy { it.title }

    fun addBook(book: Book) = apply { books[book.id] = book }
    fun addMember(member: Member) = apply { members[member.id] = member }

    fun findBook(id: Int): Book? = books[id]
    fun search(text: String) = books.values.filter {
        it.title.contains(text, ignoreCase = true) || it.author.contains(text, ignoreCase = true)
    }
}

fun main() {
    val lib = Library()
        .addBook(Book(1, "Dune", "Frank Herbert", Genre.FICTION))
        .addBook(Book(2, "Cosmos", "Carl Sagan", Genre.SCIENCE))
        .addBook(Book(3, "SPQR", "Mary Beard", Genre.HISTORY))
        .addMember(Member(1, "Ana"))

    println(lib.catalogue.map { it.title })
    println(lib.findBook(2)?.title ?: "not found")
    println(lib.findBook(9)?.title ?: "not found")
    println(lib.search("sagan").map { it.title })
}
[Cosmos, Dune, SPQR]
Cosmos
not found
[Cosmos]

addBook returns the library itself via apply, which lets us chain the setup calls.

Step 3: Borrowing with a sealed result

Borrowing can fail in several ways: unknown book, unknown member, book already on loan, member has too many books. Instead of exceptions or magic strings, a sealed interface describes every outcome, and when forces the caller to handle each one.

kotlin · try it yourself
enum class Genre { FICTION, SCIENCE, HISTORY, KIDS }
data class Book(val id: Int, val title: String, val author: String, val genre: Genre)
data class Member(val id: Int, val name: String)
data class Loan(val bookId: Int, val memberId: Int, val day: Int)

sealed interface BorrowResult {
    data class Success(val loan: Loan, val dueDay: Int) : BorrowResult
    data class NotFound(val what: String) : BorrowResult
    data class AlreadyOnLoan(val title: String) : BorrowResult
    data object LimitReached : BorrowResult
}

class Library(private val maxLoans: Int = 2, private val loanDays: Int = 14) {
    private val books = mutableMapOf<Int, Book>()
    private val members = mutableMapOf<Int, Member>()
    private val loans = mutableListOf<Loan>()

    fun addBook(book: Book) = apply { books[book.id] = book }
    fun addMember(member: Member) = apply { members[member.id] = member }

    fun borrow(bookId: Int, memberId: Int, day: Int): BorrowResult {
        val book = books[bookId] ?: return BorrowResult.NotFound("book $bookId")
        members[memberId] ?: return BorrowResult.NotFound("member $memberId")
        if (loans.any { it.bookId == bookId }) return BorrowResult.AlreadyOnLoan(book.title)
        if (loans.count { it.memberId == memberId } >= maxLoans) return BorrowResult.LimitReached
        val loan = Loan(bookId, memberId, day)
        loans += loan
        return BorrowResult.Success(loan, day + loanDays)
    }
}

fun describe(r: BorrowResult) = when (r) {
    is BorrowResult.Success -> "OK: book ${r.loan.bookId}, due on day ${r.dueDay}"
    is BorrowResult.NotFound -> "Not found: ${r.what}"
    is BorrowResult.AlreadyOnLoan -> "'${r.title}' is already on loan"
    BorrowResult.LimitReached -> "Loan limit reached"
}

fun main() {
    val lib = Library()
        .addBook(Book(1, "Dune", "Frank Herbert", Genre.FICTION))
        .addBook(Book(2, "Cosmos", "Carl Sagan", Genre.SCIENCE))
        .addBook(Book(3, "SPQR", "Mary Beard", Genre.HISTORY))
        .addMember(Member(1, "Ana"))
        .addMember(Member(2, "Ben"))

    println(describe(lib.borrow(1, 1, day = 0)))
    println(describe(lib.borrow(1, 2, day = 1)))
    println(describe(lib.borrow(2, 1, day = 2)))
    println(describe(lib.borrow(3, 1, day = 3)))
    println(describe(lib.borrow(7, 2, day = 3)))
}
OK: book 1, due on day 14
'Dune' is already on loan
OK: book 2, due on day 16
Loan limit reached
Not found: book 7

Notice ?: return …: the Elvis operator with return exits early when a lookup returns null, keeping the happy path un-indented.

Step 4: Returns and late fees

Returning a book removes the loan and calculates a fee: 0.25 per day late, capped at 5.00. The fee rule is a small pure function — easy to test on its own.

kotlin · try it yourself
data class Loan(val bookId: Int, val memberId: Int, val day: Int)

const val LOAN_DAYS = 14
const val FEE_PER_DAY = 0.25
const val MAX_FEE = 5.0

fun lateFee(loan: Loan, returnDay: Int): Double {
    val daysLate = (returnDay - (loan.day + LOAN_DAYS)).coerceAtLeast(0)
    return (daysLate * FEE_PER_DAY).coerceAtMost(MAX_FEE)
}

class LoanDesk {
    private val loans = mutableListOf<Loan>()
    private val fees = mutableMapOf<Int, Double>()   // memberId -> total fees

    fun lend(loan: Loan) { loans += loan }

    fun giveBack(bookId: Int, day: Int): String {
        val loan = loans.find { it.bookId == bookId } ?: return "Book $bookId was not on loan"
        loans.remove(loan)
        val fee = lateFee(loan, day)
        if (fee > 0) fees.merge(loan.memberId, fee, Double::plus)
        return if (fee > 0) "Book $bookId returned late, fee ${"%.2f".format(fee)}" else "Book $bookId returned on time"
    }

    fun feesOf(memberId: Int) = fees[memberId] ?: 0.0
}

fun main() {
    val desk = LoanDesk()
    desk.lend(Loan(bookId = 1, memberId = 1, day = 0))
    desk.lend(Loan(bookId = 2, memberId = 1, day = 0))
    desk.lend(Loan(bookId = 3, memberId = 2, day = 5))

    println(desk.giveBack(1, day = 10))
    println(desk.giveBack(2, day = 20))
    println(desk.giveBack(3, day = 60))
    println(desk.giveBack(3, day = 61))
    println("Ana owes ${desk.feesOf(1)}, Ben owes ${desk.feesOf(2)}")
}
Book 1 returned on time
Book 2 returned late, fee 1.50
Book 3 returned late, fee 5.00
Book 3 was not on loan
Ana owes 1.5, Ben owes 5.0

Map.merge(key, value, Double::plus) adds to an existing total or inserts the first value — a compact way to accumulate.

Step 5: Reports

Finally, put it all together and produce a report with collection operations: books per genre, who has what on loan, and an alphabetical list of available titles. An extension function formats a list of books.

kotlin · try it yourself
enum class Genre { FICTION, SCIENCE, HISTORY, KIDS }
data class Book(val id: Int, val title: String, val author: String, val genre: Genre)
data class Member(val id: Int, val name: String)
data class Loan(val bookId: Int, val memberId: Int, val day: Int)

fun List<Book>.titles() = if (isEmpty()) "-" else joinToString(", ") { it.title }

class Library {
    private val books = mutableMapOf<Int, Book>()
    private val members = mutableMapOf<Int, Member>()
    private val loans = mutableListOf<Loan>()

    fun addBook(book: Book) = apply { books[book.id] = book }
    fun addMember(member: Member) = apply { members[member.id] = member }
    fun lend(bookId: Int, memberId: Int, day: Int) = apply { loans += Loan(bookId, memberId, day) }

    fun report(): String = buildString {
        appendLine("== Library report ==")
        appendLine("Books: ${books.size}, on loan: ${loans.size}")

        appendLine("By genre:")
        books.values.groupingBy { it.genre }.eachCount()
            .toSortedMap()
            .forEach { (genre, n) -> appendLine("  ${genre.name.lowercase().padEnd(8)} $n") }

        appendLine("On loan:")
        loans.groupBy { it.memberId }.toSortedMap().forEach { (memberId, memberLoans) ->
            val name = members[memberId]?.name ?: "unknown"
            val list = memberLoans.mapNotNull { books[it.bookId] }
            appendLine("  $name: ${list.titles()}")
        }

        val loanedIds = loans.map { it.bookId }.toSet()
        val available = books.values.filter { it.id !in loanedIds }.sortedBy { it.title }
        append("Available: ${available.titles()}")
    }
}

fun main() {
    val lib = Library()
        .addBook(Book(1, "Dune", "Frank Herbert", Genre.FICTION))
        .addBook(Book(2, "Cosmos", "Carl Sagan", Genre.SCIENCE))
        .addBook(Book(3, "SPQR", "Mary Beard", Genre.HISTORY))
        .addBook(Book(4, "Matilda", "Roald Dahl", Genre.KIDS))
        .addBook(Book(5, "Emma", "Jane Austen", Genre.FICTION))
        .addMember(Member(1, "Ana"))
        .addMember(Member(2, "Ben"))
        .lend(1, 1, day = 0)
        .lend(4, 2, day = 2)
        .lend(2, 1, day = 3)

    println(lib.report())
}
== Library report ==
Books: 5, on loan: 3
By genre:
  fiction  2
  science  1
  history  1
  kids     1
On loan:
  Ana: Dune, Cosmos
  Ben: Matilda
Available: Emma, SPQR

toSortedMap() on enum keys sorts by declaration order (enums are Comparable by ordinal), which is why fiction comes before science.

Ideas to extend the project

  1. Reservations: let a member reserve a book that's on loan; when it's returned, lend it to the first person in the queue (ArrayDeque).
  2. Search filters: combine genre, author and "available only" filters with nullable parameters: fun search(genre: Genre? = null, availableOnly: Boolean = false).
  3. Persistence: serialise the library to JSON with kotlinx.serialization (in a real project).
  4. Coroutines: simulate loading the catalogue from a server with suspend fun loadCatalogue() and delay.
  5. Tests: write unit tests for lateFee covering on-time, late and capped cases.

Tip: Notice how each step kept the rules (late fees, borrow checks) in small functions with clear inputs and outputs. That's what makes the code easy to extend — and to move into a shared Kotlin Multiplatform module later.

Test yourself

Why does Library expose catalogue as a List<Book> while storing books in a private MutableMap?

  1. Maps are slower
  2. So outside code can read the books but can't modify the library's state directly
  3. Lists use less memory
  4. It is required by data classes

What does val book = books[id] ?: return BorrowResult.NotFound("book") do when the id is unknown?

  1. Throws an exception
  2. Assigns null to book
  3. Returns NotFound from the function immediately
  4. Loops again

Why is a sealed interface a good fit for BorrowResult?

  1. It makes the code run faster
  2. Each outcome can carry its own data and when must handle all cases
  3. It allows inheritance from any file
  4. It converts results to strings