Project
Expense Tracker (CLI)
Goal: Build a real command-line app that records your daily spending, saves it to a text file, and prints tables and summaries. Time: ~6–7 hours · Uses: Parts 1–8 only (no inheritance, no sealed classes, no coroutines, no Gradle — plain
kotlinc)
Project brief
Meera wants to know where her salary goes every month — rent, groceries, the auto fare, the odd Swiggy order, in Bengaluru. In this project you build a small terminal tool that answers that from the command line.
This demo runs in a scratch folder on a copy of the 7 sample expenses (see ▶️ How to run
below), so the new expense gets id #8:
$ java -jar expense-tracker.jar add 150 auto 2026-11-20 "Evening auto back home"
Added expense #8: ₹150.00 on auto (2026-11-20)
$ java -jar expense-tracker.jar summary 2026-11
Summary for 2026-11
===================
Category Amount Share
----------------------------------
rent ₹18,000.00 92.2%
...
Files
| File | What it is |
|---|---|
README.md |
This brief and the step-by-step build guide |
Expense.kt |
The one domain class — a plain class (Part 7), not a data class (that's Part 9, Stage 2) |
ExpenseTracker.kt |
Complete reference solution (try building your own first!) — main() and every command |
sample_expenses.txt |
7 sample expenses to test with |
tests_manual.md |
Commands 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, no build tool — just kotlinc and java,
exactly the pattern Part 1 established:
kotlinc Expense.kt ExpenseTracker.kt -include-runtime -d expense-tracker.jar
java -jar expense-tracker.jar help
java -jar expense-tracker.jar add 250 food 2026-11-21 "Dinner delivery"
java -jar expense-tracker.jar list
java -jar expense-tracker.jar reads and writes expenses.txt in the current directory
(there is no stdlib-only equivalent of "the folder this script lives in" without a build tool,
so this program keeps it simple: wherever you run the command from is where the data file
lives — the same convention the Java course's version of this project uses). The file is
created on the first add.
To test safely, work in a separate scratch folder on a copy of the sample data, so your real
expenses.txt is never touched:
mkdir -p /tmp/expense-test && cp sample_expenses.txt /tmp/expense-test/expenses.txt
cd /tmp/expense-test
java -jar /path/to/expense-tracker.jar list
Features
| Command | What it does | Example |
|---|---|---|
add <amount> <category> [date] [note] |
Add an expense. date is YYYY-MM-DD or the word today (default: today). note needs quotes if it has spaces. |
add 1200 auto 2026-10-12 "Airport drop" |
list [month|all] [category] |
Show expenses in a table with a total. Say all for the month slot to filter by category only. |
list 2026-11 rent |
summary [month|all] |
Total, per-category totals with % share, biggest expense | summary 2026-10 |
delete <id> |
Delete one expense by its id | delete 3 |
help |
Show the command list | help |
Error handling: bad input prints a clear Error: ... line to stderr and the program
exits with code 1. No command at all exits with code 2 (usage error), matching the
convention 0 = OK, 1 = your mistake, 2 = how you called the program.
| Bad input | Message |
|---|---|
add -50 food 2026-11-20 |
Error: Amount must be at least ₹0.01, got -50. |
add abc food 2026-11-20 |
Error: Amount must be a number, got 'abc'. |
add 100 food 2026-02-30 |
Error: Date must be a real date in YYYY-MM-DD format, got '2026-02-30'. |
delete 99 |
Error: No expense with id 99. |
Which Parts each feature uses
| Feature | Skills | Part |
|---|---|---|
String templates, Double amounts, Int ids, when for the date default |
val/var, string templates, when as an expression |
Part 2 |
String?/Int? from toDoubleOrNull()/toIntOrNull(), the ?: elvis to turn a null into an error |
nullable types, safe calls, elvis | Part 3 |
Filters, loops, when on the command |
if/else, for, when, early return |
Part 4 |
One job per top-level fun, default-free parameters, a small local when inside handleAdd |
functions, parameters/return types | Part 5 |
MutableList<Expense>, filter/sortedWith/groupBy/sumOf/maxByOrNull used as ready-made tools |
List/MutableList, the Part 6 collection toolkit |
Part 6 |
class Expense with a primary constructor and an init block that validates it |
plain classes, init blocks, require |
Part 7 |
expenses.txt load/save with java.io.File, readLines/forEachLine/writeText |
java.io.File, reading and writing text |
Part 8 |
add, list, summary, delete dispatch, raw Array<String> |
reading main(args: Array<String>) by hand (no library — Kotlin inherits Java's lack of a stdlib argparse) |
New here |
💡 The only class in this solution is
Expenseitself (Part 7) — a plainclass, deliberately not adata class.data class, with theequals()/hashCode()/toString()it generates for free, is Part 9's lesson in Stage 2; writingtoLine()by hand here is the honest cost of "no generated code yet." There is also no custom exception class: Kotlin has no checked exceptions, and Part 3 already established the idiom this project leans on throughout —throw IllegalArgumentException("...")for anything the user can fix, caught once inmain(). A realExpenseExceptionsubclass would needclass X : Exception(...), which is inheritance (Part 9, Stage 2) — out of scope here on purpose.
Small new tools you will meet
| Tool | What it does | Example |
|---|---|---|
file.exists() |
true if the file is there — a missing file just means "no expenses yet" |
Step 1 |
file.forEachLine { ... } |
stream through a text file one line at a time, without loading it all into memory first | Step 1 |
file.writeText(text) |
overwrite a file with a whole String in one call |
Step 1 |
line.split("|") |
split a line on | into a List<String> |
Step 1 |
text.toDoubleOrNull() / text.toIntOrNull() |
parse-or-null instead of parse-or-throw — the Kotlin-idiomatic way to validate user text |
Step 2 |
String.format(Locale.US, "₹%,.2f", x) |
format a number with commas and 2 decimals, locale-independent | Step 2/4 |
Math.round(x * 100) / 100.0 |
round to paise (2 decimals) before validating | Step 2 |
LocalDate.of(year, month, day) |
throws DateTimeException for a date that doesn't exist, like Feb 30 |
Step 2 |
list.sortedWith(compareBy({ ... }, { ... })) |
sort by two keys, like Python's sorted(key=...) |
Step 3 |
list.groupBy { ... }.mapValues { ... } |
group then total, instead of a hand-rolled running-total map | Step 4 |
when (args[0]) { "add" -> ...; else -> ... } |
one branch per command, no break needed |
Step 5 |
Build it step by step
Build in small steps. Compile and run after every step. Do not open ExpenseTracker.kt
until you have tried each step yourself.
Step 1: Model one expense, and load/save the text file (Parts 7, 8)
What and why: unlike the Java course's version of this project (which has no classes until
Stage 2), Kotlin's Part 7 already covers plain classes — so this project starts with a real
class Expense, one object per row, instead of five parallel lists:
class Expense(
val id: Int,
val date: String,
val amount: Double,
val category: String,
val note: String
) {
init {
require(id > 0) { "Expense id must be positive, got $id." }
require(amount > 0.0) { "Expense amount must be positive, got $amount." }
require(category.isNotBlank()) { "Expense category cannot be blank." }
}
fun toLine(): String {
val amountText = String.format(java.util.Locale.US, "%.2f", amount)
return "$id|$date|$amountText|$category|$note"
}
}
The init block is a safety net, not the first line of defence — parseAmount/parseDate/
cleanCategory (Step 2) already reject bad user input before an Expense is ever constructed.
Open sample_expenses.txt. Each line is one expense, fields separated by |:
id|date|amount|category|note.
fun loadExpenses(file: File): MutableList<Expense> {
val expenses = mutableListOf<Expense>()
if (!file.exists()) return expenses
file.forEachLine { line ->
// split on "|", validate, Expense(...), add — see Step 1 "Going deeper" below
}
return expenses
}
fun saveExpenses(file: File, expenses: List<Expense>) {
val text = expenses.joinToString("\n") { it.toLine() }
file.writeText(if (text.isEmpty()) "" else "$text\n")
}
✅ Test: loadExpenses(File("sample_expenses.txt")).size → 7.
🔍 Going deeper:
writeText()replaces the whole file every time — simple, and fine for a personal file with a few hundred lines. A real database never rewrites everything; it appends. An atomic save (write to a.tmpfile, then rename it over the real one, so a crash mid-write can't corrupt the file) is a good stretch goal here, same as the Java and Python versions of this project note.Why
|and not a comma? Notes are free text and might contain commas ("Full tank, scooter");|is rare enough in an English sentence that a flat split works. This is a real limitation — a note containing|would break parsing — the same trade-off the Java course's version of this project makes, and for the same reason: no JSON parser ships in the plain JDK/Kotlin stdlib without a dependency.
Step 2: Validate and add an expense (Parts 2, 3, 5)
What and why: this is the main job of the app. Clean the user's text first, so the saved
data is always neat. Kotlin's idiom for "parse this or fail" is parse-or-null, then an
?: to turn the null into a thrown exception — not a try/catch around a parse call:
fun parseAmount(text: String): Double {
val raw = text.toDoubleOrNull()
?: throw IllegalArgumentException("Amount must be a number, got '$text'.")
if (!raw.isFinite()) throw IllegalArgumentException("Amount must be a normal number, got '$text'.")
val amount = Math.round(raw * 100) / 100.0 // round FIRST: 0.001 becomes 0.0
if (amount <= 0) throw IllegalArgumentException("Amount must be at least ₹0.01, got $text.")
return amount
}
- New id = biggest id + 1 (loop and track a running max — no
max()shortcut with a default, so write the loop yourself, same as the Java version). - Date: split on
-, build threeInts, callLocalDate.of(year, month, day)insidetry/catch (e: DateTimeException)— that call throws for2026-02-30because February never has a 30th. - Category:
text.trim().lowercase(). ThrowIllegalArgumentExceptionif it is empty.
✅ Test: add one expense to a copy of the sample file and open expenses.txt. You should see
id 8 on the last line.
🔍 Going deeper: why round before comparing to zero?
0.001rounds to0.00, which should be refused with a clear message, not silently saved as₹0.00. Checking<= 0before rounding would let0.001through as "positive," then save a useless0.00expense. Order matters with floating-point money — real banks store paise as aLong, not aDouble, for exactly this reason.
Step 3: List with filters (Parts 4, 6)
What and why: you rarely want to see everything. Filters answer "What did I spend in
November?" — using Part 6's filter/sortedWith as ready-made tools, the same way the lesson
itself used filter/map/sumOf:
fun matchingExpenses(expenses: List<Expense>, month: String?, category: String?): List<Expense> =
expenses
.filter { month == null || it.date.substring(0, 7) == month }
.filter { category == null || it.category == category }
.sortedWith(compareBy({ it.date }, { it.id }))
Print a table with String.format: %-10s left-pads, %12s right-pads, matching the same
alignment idea as printf in other languages.
✅ Test: list 2026-11 shows 3 rows and Total ₹19,364.00.
Step 4: Summary (Part 6)
What and why: a list shows every rupee; a summary shows the big picture: which category eats most of the month.
- Total:
matches.sumOf { it.amount }. - Per category:
matches.groupBy { it.category }.mapValues { (_, group) -> group.sumOf { it.amount } }— group then total in two calls, no hand-rolled running-total map needed. - Sort the grouped totals descending with
sortedByDescending. - Biggest expense:
matches.maxByOrNull { it.amount }— a ready-made tool instead of a hand-written loop tracking the largest index.
✅ Test: summary 2026-10 shows rent at 81.0% and total ₹22,220.75.
Step 5: Delete by id (Part 4)
What and why: everyone types a wrong amount sometimes. Delete lets you fix it (then add it again).
expenses.find { it.id == id }— Kotlin's ready-made "find the first match or null," instead of a hand-written loop with a sentinel index.?: throw IllegalArgumentException(...)if nothing matched.expenses.remove(expense)— one call on oneMutableList<Expense>, not five parallel removals at the same index the way the Java version of this project needs.- Save after deleting.
✅ Test: delete 6 works once. Running it again gives Error: No expense with id 6.
Step 6: Reading args by hand (new — Part 2, Part 4's when)
What and why: Kotlin ships no argparse either — main(args: Array<String>) is just an
array of the words typed after java -jar expense-tracker.jar, read the same way you'd read
any array: by index and size.
fun main(args: Array<String>) {
if (args.isEmpty()) { /* usage error, exit 2 */ }
when (args[0]) {
"add" -> handleAdd(rest, expenses, dataFile)
"list" -> handleList(rest, expenses)
"summary" -> handleSummary(rest, expenses)
"delete" -> handleDelete(rest, expenses, dataFile)
else -> throw IllegalArgumentException("Unknown command '${args[0]}'. ...")
}
}
Each handleX checks args.size itself (e.g. add needs 2 to 4 words after the command name)
and throws IllegalArgumentException with a one-line "Usage: ..." message on a bad count.
There's no --note "text" flag syntax — arguments are purely positional:
add <amount> <category> [date] [note]. To skip the month filter while still filtering by
category, type the word all in the month's place: list all groceries.
✅ Test: java -jar expense-tracker.jar help and java -jar expense-tracker.jar (no args) —
compare their exit codes with echo $?.
Step 7: Error handling (Part 3's idiom, used everywhere)
What and why: users type mistakes. A beginner app crashes with a stack trace; a good app prints one clear line and stops.
- No custom exception class. Kotlin has no checked exceptions — there is nothing for a
custom
Exceptionsubclass to buy you here thatIllegalArgumentExceptiondoesn't already give for free, and subclassingExceptionis inheritance (Part 9, Stage 2 — out of scope). - Every validation helper throws
IllegalArgumentExceptionwith a clear message (amount, date, month, id, category — see Step 2). - Loading the file also throws it for a broken line (wrong field count, bad id/amount, bad
date) — so a hand-edited
expenses.txtfails loudly instead of corrupting silently. main()catchesIllegalArgumentExceptionin one place, prints toSystem.err, and exits1. A separatecatch (e: IOException)handles real file problems (permission denied, folder missing) with exit1too. Anything else (a real bug) is not caught — it should still crash loudly with a stack trace so you can fix it.
✅ Test: run every error case in tests_manual.md. Each should print
Error: ... to stderr and exit 1 (or 2 for no command at all).
Stretch goals
- 🟢
categoriescommand: print all categories used so far. - 🟢
list --sort amount-equivalent: sort by amount instead of date (add a 3rd positional mode). - 🟡
edit <id>to change an expense's amount/category/note/date. - 🟡 Monthly budget: a
budget.txtwith one limit per category;summarywarns when a category goes over. - 🟡 Atomic save: write to
expenses.txt.tmpthen rename it overexpenses.txt(see Step 1's "Going deeper"). - 🟡 A
--file <path>global option, parsed by hand before dispatching on the command. - 🔴 Turn
Expenseinto adata classonce you've done Part 9, and compare how much oftoLine()/equality you get "for free" versus writing it by hand here. - 🔴 Indian number format:
₹1,50,000.00instead of₹150,000.00(write your own grouping function —String.formatcan't do this directly).
Checklist
- I can model one record as a plain
classwith a validatinginitblock. - I can read and write a plain text file with
java.io.File. - I can filter and sort data with
filter/sortedWithas ready-made tools. - I can group and total data with
groupBy/mapValues/sumOf. - I can print an aligned table with
String.format. - I can validate a date with
LocalDate.of(...)and catchDateTimeException. - I can throw
IllegalArgumentExceptionwith a clear message and catch it in one place inmain(), and I can explain why this project defines no custom exception class. - I can read
args: Array<String>by hand and dispatch on it withwhen. - All commands in
tests_manual.mdgive the expected output and exit code.
Next
🎉 Stage 1 done! Go back to the roadmap and start Stage 2, Part 9:
Object-oriented Kotlin in depth. Good idea: rebuild this tracker there with Expense as a
data class, and see exactly how much code disappears.