Project
Library Management System (CLI)
Goal: Build a real command-line library system — books, members, loans — with your own class hierarchy, sealed result types instead of exceptions, idiomatic collections/functional pipelines, and real
kotlin.test/JUnit 5 tests. Time: ~8 hours · Uses: Parts 9–11 (plus everything from Stage 1)
Project brief
A small college library still runs on a register: who took which book, when is it due, who owes a fine. In this project you replace that register with a tool you run from the terminal.
The library has three rules:
| Rule | Value |
|---|---|
| Books one member can have at the same time | 3 |
| Loan period | 14 days |
| Late fee | ₹5 per day late |
A real run against the sample data (the full script is in tests_manual.md):
$ java -jar library-manager.jar --dir demo --today 2026-11-26 borrow 1 9
Loan #4: 'Chemmeen' to Priya Nair, due 2026-12-10.
$ java -jar library-manager.jar --dir demo --today 2026-11-26 return 1
Returned 'Train to Pakistan' (loan #1): 23 days late, fee ₹115.00.
$ java -jar library-manager.jar --dir demo --today 2026-11-26 report
Library report
===============
Books: 9 total, 7 available
Members: 5
Loans: 2 active, 1 overdue
Fees collected so far: ₹115.00
Files
| File | What it is |
|---|---|
README.md |
This brief and the step-by-step build guide |
Book.kt, Member.kt, Loan.kt |
The three model classes — try building these yourself first! |
BookStatus.kt |
Enum with a field: AVAILABLE/ON_LOAN, each with its own display label |
LibraryRecord.kt |
A tiny interface with a default method, implemented by Book/Member/Loan |
LibraryReport.kt |
Plain-data data classes used for reporting (LibraryReport, OverdueEntry) |
Results.kt |
The sealed result hierarchies every library action returns, instead of exceptions |
UsageException.kt |
The one exception class in this project — for a command line that doesn't parse |
LibraryRepository.kt |
Persistence: three flat files (books.txt/members.txt/loans.txt), no database |
Library.kt |
The business rules: borrow, return, overdue, report |
LibraryManager.kt |
The command-line entry point (complete reference solution) |
sample_data.txt |
8 books, 4 members and 3 loans to play with |
lib/ |
The three jars the test run needs, downloaded once (not committed — see "Running the tests") |
tests/ |
kotlin.test/JUnit 5 tests: ModelsTest, LibraryRepositoryTest, LibraryTest |
tests_manual.md |
Every CLI command to try, with the exact expected output |
How to run
Open a terminal in this folder (kotlinc 2.4.21, JDK 21 Corretto — see
../../TOOLING.md). No Gradle — this course hasn't verified a Gradle build
on this machine (see Part 11's README), so, like Part 11 itself, this project compiles and
runs with plain kotlinc/java:
kotlinc *.kt -include-runtime -d library-manager.jar
java -jar library-manager.jar help
java -jar library-manager.jar --dir demo load-sample sample_data.txt
java -jar library-manager.jar --dir demo list-books
By default your data is saved as books.txt/members.txt/loans.txt in the current
directory. The files are created the first time you run any command. To test safely, pass
--dir demo to use a scratch subfolder, so your real data is never touched — see
tests_manual.md for the full script.
Global options go before the command:
| Option | What it does |
|---|---|
--dir PATH |
Use another data directory, e.g. --dir demo for testing |
--today YYYY-MM-DD |
Pretend today is this date. Makes due dates, overdue reports and fees reproducible |
Running the tests
This machine has no Gradle, the same situation Part 11
documents — so tests run the way Part 11's section 7 verified: kotlinc plus the JUnit
Platform Console standalone launcher, with kotlin.test's JUnit 5 engine on the classpath.
The three jars (the exact versions Part 11 downloaded) live in lib/:
$ curl -sS -o lib/junit-platform-console-standalone-1.14.5.jar \
https://repo1.maven.org/maven2/org/junit/platform/junit-platform-console-standalone/1.14.5/junit-platform-console-standalone-1.14.5.jar
$ curl -sS -o lib/kotlin-test-2.3.21.jar \
https://repo1.maven.org/maven2/org/jetbrains/kotlin/kotlin-test/2.3.21/kotlin-test-2.3.21.jar
$ curl -sS -o lib/kotlin-test-junit5-2.3.21.jar \
https://repo1.maven.org/maven2/org/jetbrains/kotlin/kotlin-test-junit5/2.3.21/kotlin-test-junit5-2.3.21.jar
Then, exactly like Part 11 section 7 — compile main and test into separate output
directories (reusing one directory for both silently corrupts cross-file metadata, Part 11
section 8's whole point), and run everything through the console launcher:
mkdir -p build
kotlinc *.kt -d build/classes/main
kotlinc -cp "build/classes/main:lib/junit-platform-console-standalone-1.14.5.jar:lib/kotlin-test-2.3.21.jar:lib/kotlin-test-junit5-2.3.21.jar" \
tests -d build/classes/test
java -jar lib/junit-platform-console-standalone-1.14.5.jar execute \
--classpath "build/classes/main:build/classes/test:lib/kotlin-test-2.3.21.jar:lib/kotlin-test-junit5-2.3.21.jar:$(readlink -f $(which kotlinc) | xargs dirname | xargs dirname)/libexec/lib/kotlin-stdlib.jar" \
--scan-classpath --details=tree --disable-ansi-colors
[ 7 containers found ]
[ 7 containers successful ]
[ 28 tests found ]
[ 28 tests successful ]
[ 0 tests failed ]
(The real counts from a verified run — (varies) only if you add or remove tests.) Note the
kotlin-stdlib.jar path above resolves the real Homebrew Cellar directory through
readlink -f, rather than Part 11's $(dirname $(which kotlinc))/../libexec/lib/... —
on this machine /opt/homebrew/bin/kotlinc is a symlink into Cellar/kotlin/2.4.21/bin/, and
../libexec from the symlink's own directory doesn't exist; resolving the symlink first is
the fix. Run kotlinc -version and readlink -f $(which kotlinc) yourself if this path needs
adjusting on a different machine.
Features
| Command | What it does | Example |
|---|---|---|
add-book <title> <author> <year> |
Add a book | add-book "A Suitable Boy" "Vikram Seth" 1993 |
add-member <name> <email> |
Add a member (each email only once) | add-member "Kabir Khan" [email protected] |
list-books [available] |
Show all books, or only the ones on the shelf | list-books available |
search <text> |
Find books by title or author (any letter case) | search narayan |
borrow <memberId> <bookId> |
Lend a book. Due 14 days later. Max 3 books per member | borrow 1 6 |
return <loanId> |
Take a book back. ₹5 per day late | return 1 |
overdue |
Loans past their due date, with the fee so far | --today 2026-12-20 overdue |
report |
Totals: books, members, loans, fees collected | report |
load-sample <path> |
Load a sample-data file into an empty library | --dir demo load-sample sample_data.txt |
help |
Show the command list | help |
Error handling: a library-rule mistake prints one clear Error: ... line to stderr and
exits with code 1. Wrong usage (an unknown option, a missing command, an unparseable
--today) exits with code 2.
| Bad input | Message |
|---|---|
borrow 1 6 (member already has 3 books) |
Error: Priya Nair already has 3 books on loan (limit 3). |
borrow 2 9 (book is out) |
Error: 'The White Tiger' is already on loan. |
borrow 99 1 |
Error: No member with id 99. |
return 99 |
Error: No loan with id 99. |
add-member "Riya Das" riya.example.com |
Error: Email must contain '@', got 'riya.example.com'. |
Architecture
Each layer only talks to the one below it — the same separation the Stage 1 project and the Java course's version of this project both keep, with a real class per responsibility:
you type a command
│
▼
┌───────────────────────────┐
│ LibraryManager (CLI) │ reads args, prints tables, "Error: ..." + exit codes
└────────────┬──────────────┘
│ calls library.borrow(1, 6, today) -> a BorrowResult
▼
┌───────────────────────────┐
│ Library │ the RULES (3 books max, 14 days, ₹5/day), returns sealed results
└────────────┬──────────────┘
│ calls repository.findBook(6), repository.insertLoan(loan) ...
▼
┌───────────────────────────┐
│ LibraryRepository │ all the file I/O, id assignment, in-memory lists
└────────────┬──────────────┘
▼
books.txt / members.txt / loans.txt
Book / Member / Loan / BookStatus and the Results.kt sealed classes
are used by every layer.
Why split it like this?
- Easy to test:
LibraryTesttests the rules against a throwaway temp directory, with no command line involved. - Easy to change: a future web front end could call the same
Libraryclass; onlyLibraryManagerwould change.
🔍 Why flat files, not a database? The Java course's version of this project uses SQLite over JDBC, taught in its own Part 11 ("I/O APIs and databases"). This Kotlin course's Part 11 covers something different — Gradle-less testing, not JDBC — so there is no database skill to build on yet.
LibraryRepositoryreuses Stage 1'sjava.io.File+|-delimited-line approach instead, the honest "what Stage 1–11 have actually taught" choice. A real SQLite-backed version is a 🔴 stretch goal below, once Part 12 (Java interop) or a later content wave introduces JDBC from Kotlin.
Which Parts each piece uses
| Piece | Skills | Part |
|---|---|---|
Book, Member, Loan as classes with validating init blocks |
constructors, init, require, properties with a non-property constructor parameter (Member's email) |
Part 7, Part 9 |
LibraryRecord interface with a default describe() method |
interfaces with default methods | Part 9, section 2 |
BookStatus |
enum with a field (label) |
Part 9, section 7 |
Book/Member/Loan's hand-written equals/hashCode/toString, by id |
overriding Any's methods, and why these are plain classes, not data class |
Part 9, section 5 |
Results.kt's sealed hierarchies, exhaustive when in LibraryManager |
sealed classes/results instead of exceptions | Part 9, section 6 |
LibraryReport, OverdueEntry |
plain, immutable data → data class |
Part 9, section 4 |
Library.MAX_LOANS_PER_MEMBER etc. on a companion object |
object/companion object |
Part 9, section 8 |
UsageException |
a one-off, deliberate use of inheritance (class X : Exception(...)) — fair game now that Part 9 has taught it |
Part 9 |
Library.overdue's asSequence().map{}.filter{}, repository.searchBooks's filter{}, handleReport's StringBuilder().apply{} |
Sequence vs. eager collections, higher-order functions, scope functions |
Part 10 |
repository.findBook(id) returning Book?, ?: for a fallback |
nullable types instead of Optional/null-checking |
Stage 1, Part 3 |
tests/ModelsTest.kt, LibraryTest.kt, LibraryRepositoryTest.kt |
@Test, @BeforeTest/@AfterTest, assertFailsWith, assertIs, @ParameterizedTest + @CsvSource |
Part 11 |
LibraryManager.main, when dispatch, exit codes |
reading args by hand, same convention as the Stage 1 project |
Stage 1 project |
Build it step by step
Build in small steps. Compile and run after every step. Try each one yourself before
opening the finished .kt files in this folder.
Step 1: Models, an interface, and an enum (Part 9)
What and why: decide the shape of one book/member/loan before writing any rule. A shared
LibraryRecord interface gives every model an id and a one-line summary(), plus a free
describe() default method built out of them:
interface LibraryRecord {
val id: Int?
fun summary(): String
fun describe(): String = "#${id ?: "?"}: ${summary()}"
}
Book is a plain class, not a data class — id is null until the repository assigns
one, and status genuinely changes while it's "the same" book, so equals/hashCode are
hand-written by id instead of generated from every property:
class Book(
override var id: Int? = null,
val title: String, val author: String, val year: Int,
var status: BookStatus = BookStatus.AVAILABLE
) : LibraryRecord {
init {
require(title.isNotBlank()) { "Title cannot be empty." }
require(year in 1000..2100) { "Year must be a real year, got $year." }
}
override fun equals(other: Any?) = other is Book && id != null && other.id == id
override fun hashCode() = id?.hashCode() ?: 0
}
BookStatus is an enum with a field — AVAILABLE/ON_LOAN carry a display label the CLI
prints, separate from the plain name stored in books.txt. Member validates its email
contains @ and lowercases it. Loan adds a daysLate(asOf) helper and a markReturned(...)
method — the only way returnedOn/feeRupees ever change.
✅ Test: Book(title = " ", author = "A", year = 2000) throws IllegalArgumentException;
Loan(bookId = 2, memberId = 1, borrowedOn = due.minusDays(14), dueOn = due).daysLate(due.plusDays(3)) → 3.
Step 2: Sealed results instead of exceptions (Part 9, section 6)
What and why: the Java course's version of this project throws a LibraryException
subclass per failure and catches the base class once. Kotlin's idiom for "this can fail in one
of a few known ways" is a sealed class the caller must handle exhaustively:
sealed class BorrowResult {
data class Borrowed(val loan: Loan, val bookTitle: String, val memberName: String) : BorrowResult()
data class BookNotFound(val bookId: Int) : BorrowResult()
data class MemberNotFound(val memberId: Int) : BorrowResult()
data class BookNotAvailable(val title: String) : BorrowResult()
data class LoanLimitExceeded(val memberName: String, val limit: Int) : BorrowResult()
}
There is no catch to forget here, and no silent default case if a sixth outcome gets added
later — the compiler refuses to build LibraryManager's when until every branch is handled.
✅ Test: build each BorrowResult subtype by hand and confirm is BorrowResult.Borrowed /
is BorrowResult.BookNotAvailable narrow correctly in a when.
Step 3: LibraryRepository — all the file I/O, behind one class (Part 8, Stage 1 + Part 9)
What and why: this is the only class that touches books.txt/members.txt/loans.txt.
dataDir is handed in, never hard-coded — the same dependency-injection seam Part 10 note
(and the Java course's JDBC Connection) use for testability, so a test can point this class
at a throwaway temp directory instead of a real one:
class LibraryRepository(private val dataDir: File) {
private val books = mutableListOf<Book>()
// ... loadBooks()/saveBooks() etc. on init, Part 8's java.io.File
fun insertBook(book: Book): Book {
book.id = nextId(books.map { it.id })
books.add(book)
saveBooks()
return book
}
}
insertMember is the one place a duplicate-email check happens before trying to save — see
Library.addMember in Step 4. Every other query returns a nullable Book?/Member?/Loan?
or a List<...>, Kotlin's idiom instead of Optional<T>.
✅ Test: against a temp directory, repository.insertBook(Book(title = "Malgudi Days", ...)).id
→ 1, and repository.findBook(1) reads the same row back.
🔍 Going deeper:
loadSample(sampleFile)is a deliberately small script runner — split on section headers (# BOOKS/# MEMBERS/# LOANS), skip comments and blank lines, insert each row — good enough for this project's flat seed data, not a general parser. It is whatload-samplecalls, and it refuses to run on anything but an empty library, so it only ever runs once per directory.
Step 4: Library — the rules, with constants on a companion object (Part 9, section 8)
What and why: "3 books max", "14 days", "₹5 per day" are the library's rules, not facts
about file I/O. A companion object keeps them in one place, so a rule change is a one-line
edit:
class Library(private val repository: LibraryRepository) {
companion object {
const val MAX_LOANS_PER_MEMBER = 3
const val LOAN_PERIOD_DAYS = 14L
const val LATE_FEE_PER_DAY_RUPEES = 5
}
fun borrow(memberId: Int, bookId: Int, today: LocalDate): BorrowResult {
val member = repository.findMember(memberId) ?: return BorrowResult.MemberNotFound(memberId)
val book = repository.findBook(bookId) ?: return BorrowResult.BookNotFound(bookId)
if (!book.isAvailable) return BorrowResult.BookNotAvailable(book.title)
if (repository.countActiveLoans(memberId) >= MAX_LOANS_PER_MEMBER) {
return BorrowResult.LoanLimitExceeded(member.name, MAX_LOANS_PER_MEMBER)
}
val loan = repository.insertLoan(Loan(bookId = bookId, memberId = memberId, borrowedOn = today, dueOn = today.plusDays(LOAN_PERIOD_DAYS)))
repository.updateBookStatus(bookId, BookStatus.ON_LOAN)
return BorrowResult.Borrowed(loan, book.title, member.name)
}
}
Library never touches a file itself — it only calls LibraryRepository methods, so
tests/LibraryTest.kt can test every rule against a temp directory with no CLI involved.
✅ Test: borrow 3 books for the same member, then a 4th returns
BorrowResult.LoanLimitExceeded("<name>", 3).
🔍 Going deeper: why does
borrow/returnBooktaketodayas a parameter instead of callingLocalDate.now()inside? A test written today would start failing tomorrow. Passing the date in — the same dependency-injection idea as Step 3'sdataDir— makes every test, and--todayon the command line, reproducible forever.
Step 5: Overdue report and totals — the functional pipeline (Part 10)
What and why: the librarian's daily question is "who is late, and how much?"
overdue(today) runs active loans through a Sequence, so the map/filter steps happen
lazily instead of materializing an intermediate List between each one:
fun overdue(today: LocalDate): List<OverdueEntry> =
repository.listActiveLoans()
.asSequence()
.map { loan -> loan to loan.daysLate(today) }
.filter { (_, days) -> days > 0 }
.map { (loan, days) -> OverdueEntry(loan, repository.findBook(loan.bookId)?.title ?: "unknown book", /* ... */ daysLate = days, feeRupees = days * LATE_FEE_PER_DAY_RUPEES) }
.sortedByDescending { it.daysLate }
.toList()
report(today) returns a LibraryReport data class with the totals, built with count/
sumOf instead of hand-written loops. search(text) is one filter call with
contains(text, ignoreCase = true).
✅ Test: borrow then return a book 2 days late → report(today).feesCollectedRupees includes
10.
Step 6: Tests with kotlin.test/JUnit 5, no Gradle (Part 11)
What and why: the rules are money — a test suite proves they still work after every
change. Split across three files exactly like the Java course's version: ModelsTest
(constructors, equals, daysLate — no repository at all), LibraryRepositoryTest (the file
I/O, against a temp directory), LibraryTest (the rules, through Library, also temp-backed):
class LibraryTest {
private lateinit var dir: File
private lateinit var library: Library
@BeforeTest
fun freshLibraryWithOneBookAndOneMember() {
dir = createTempDirectory("library-test").toFile()
library = Library(LibraryRepository(dir))
// ... addBook/addMember, same shape as the Java course's @BeforeEach
}
@AfterTest
fun cleanUp() { dir.deleteRecursively() }
@ParameterizedTest(name = "{0} days late costs Rs {1}")
@CsvSource("0, 0", "1, 5", "11, 55", "30, 150")
fun `returnBook charges a late fee of five rupees per day`(daysLate: Int, expectedFee: Int) {
// borrow, then returnBook at dueOn.plusDays(daysLate), assertEquals(expectedFee, ...)
}
}
A fresh temp directory for every test (@BeforeTest/@AfterTest) means one test's rows never
leak into the next. @ParameterizedTest/@CsvSource are plain JUnit 5, used directly —
kotlin.test has no parameterized-test feature of its own, the same gap Part 11 section 6
flags.
✅ Test: all 28 tests green — see "Running the tests" above for the exact command.
Step 7: LibraryManager — the CLI (Stage 1 project pattern)
What and why: this is the only class that reads args, opens the repository, and prints
anything. Global options (--dir, --today) are parsed first, then the command dispatches
with when, matching each sealed result exhaustively:
when (val result = library.borrow(memberId, bookId, today)) {
is BorrowResult.Borrowed -> println("Loan #${result.loan.id}: '${result.bookTitle}' to ${result.memberName}, due ${result.loan.dueOn}.")
is BorrowResult.BookNotFound -> fail("No book with id ${result.bookId}.")
is BorrowResult.MemberNotFound -> fail("No member with id ${result.memberId}.")
is BorrowResult.BookNotAvailable -> fail("'${result.title}' is already on loan.")
is BorrowResult.LoanLimitExceeded -> fail("${result.memberName} already has ${result.limit} books on loan (limit ${result.limit}).")
}
Exit codes: 0 success, 1 a library-rule failure (any sealed result's failure branch), 2
wrong command-line usage (UsageException) — unknown option, missing command, an unparseable
--today, the wrong number of arguments.
✅ Test: run every command and error case in tests_manual.md. Output and
exit code must match exactly.
Step 8: Sample data (Part 8, Stage 1)
What and why: a demo needs data. sample_data.txt is a plain text file with # BOOKS/
# MEMBERS/# LOANS sections, so tests_manual.md can say "book 9" and mean the same book
every time (ids are assigned in file order, starting at 1, on an empty library).
✅ Test: --dir demo load-sample sample_data.txt → Loaded sample data: 8 books, 4 members, 3 active loans.
Stretch goals
- 🟢
list-memberscommand: id, name, email and how many books each one currently has out. - 🟢
history <memberId>: every loan a member has ever taken, with dates and fees. - 🟡 More than one copy of a book: a
copiescount, comparing active loans against it instead of a singlestatus. - 🟡
renew <loanId>: add 14 more days, but only once and only if the loan is not already overdue. - 🟡 Replace
LibraryRepository's flat files with a realMap<Int, Book>index instead ofbooks.find { it.id == id }'s linear scan — fine at this project's scale, a real cost at a real library's. - 🔴 A SQLite-backed
LibraryRepository, once a later content wave introduces JDBC from Kotlin, replacing the flat files with the samejdbc:sqlite::memory:testing trick the Java course's version uses. - 🔴 A generic
Repository<T>wrapper (Part 13, Stage 3) around the three id-lookup patterns (findBook,findMember,findLoan)LibraryRepositorycurrently repeats three times.
Checklist
- I can design a small class with a validating
initblock, and writeequals/hashCodeby hand for a class with an identity (id) separate from its other fields. - I can write an interface with a default method, and an enum with a field.
- I can design a sealed result hierarchy instead of a custom exception family, and match it
exhaustively with
when. - I can keep business rules in one class with named constants on a
companion object, and passtodayin rather than reading the clock. - I can build a lazy
Sequencepipeline withmap/filter, and explain whenasSequence()actually matters. - I can write
kotlin.test/JUnit 5 tests with@BeforeTest/@AfterTest,assertFailsWith,assertIs, and@ParameterizedTest+@CsvSource, against a temp-directory repository, with no Gradle. - All 28 tests pass and every command in
tests_manual.mdgives the expected output and exit code.
Next
🎉 Stage 2 done! Go back to the roadmap and get ready for Stage 3: Advanced (generics, coroutines, internals, packaging).