Part 10 / Stage 2
Functional Kotlin
Goal: Give lambdas, higher-order functions and function references a proper treatment after using them as ready-made tools since Part 6; learn the five scope functions and when to reach for each; and understand
Sequencelaziness well enough to choose it on purpose instead of by habit. Time: ~6 hours · Level: comfortable with Part 6's collections and Part 9's classes
What you will learn
- Lambdas properly defined:
{ params -> body }, the implicitit, trailing lambda syntax, and that a lambda is a value with a function type like(Shipment) -> Boolean - Higher-order functions: taking a function as a parameter, returning one, or both
- Function references:
::functionName, bound vs unbound member references, constructor and property references - The five scope functions —
let,run,with,apply,also— and a decision rule for picking between them instead of guessing Sequencevs eagerly-evaluated collections: what "lazy" really means, proved by counting stepsfoldvsreduce, and why one of them can crash on an empty collection and the other can'tgroupBy/groupingBy().eachCount()/associateBy/partitionas a group-then-summarize pipeline- Building a small report pipeline: a lazy early-exit scan, fold/groupBy for the numbers, and scope functions to assemble the result
Topics in this part
Practice
Try each one yourself first. Then check the solution.
Every exercise is one file with a top-level fun main(), using everything from Stage 1 plus
this part's lambdas, higher-order functions, function references, scope functions, sequences,
fold/reduce and the groupBy/associateBy/partition family.
Exercise 1: Discount eligibility checker
Scenario: An online store checks orders against different eligibility rules — a function
decides what counts, the checker itself doesn't care which rule it's given.
What to do: Write data class Order(val id: String, val amountInr: Double) and a list of
four orders. Write a top-level function isBulk(order: Order) = order.amountInr > 5000.0. Write
fun eligible(orders: List<Order>, rule: (Order) -> Boolean): List<String> returning the
matching ids. Call it once with ::isBulk (a function reference) and once with a trailing
lambda checking amountInr < 200.0.
Sample output:
Bulk orders (function reference): [O-1, O-3]
Small orders (trailing lambda): [O-2, O-4]
💡 Hint: eligible(ORDERS, ::isBulk) passes the function itself, not a call to it — no
parentheses after isBulk.
Exercise 2: Salary slip references
Scenario: HR wants employee names printed via a property reference, and a payout total
computed through both a bound and an unbound member reference, to see they give the same answer.
What to do: Write data class Employee(val name: String, val salaryInr: Double) and
class SalarySlip(private val bonusInr: Double) { fun totalInr(e: Employee) = e.salaryInr + bonusInr }. Build a list of two employees. Print their names using Employee::name as a
property reference inside .map(...). Build val slip = SalarySlip(2000.0), print every
employee's total via the bound reference slip::totalInr. Then store
SalarySlip::totalInr (the unbound form) in a val typed (SalarySlip, Employee) -> Double
and call it directly on slip and the first employee, printing the result.
Sample output:
Names: [Kavita Rao, Arjun Mehta]
Totals (bound reference): [57000.0, 77000.0]
Same total via unbound reference: 57000.0
💡 Hint: the unbound reference's first parameter IS the receiver — unbound(slip, employee), not unbound(employee).
Exercise 3: Registration form with scope functions
Scenario: A signup form builds a user profile object, handles an optional age field
gracefully, and logs once the profile is ready — three small jobs, each suited to a different
scope function.
What to do: Write data class UserProfile(var displayName: String = "", var city: String = "", var isVerified: Boolean = false). Build one with apply { } (setting displayName and
city), chained into .also { } to print a one-line log. Separately, given val rawAge: String? = "29", use ?.let { } to build an "Age on file: $it" string, falling back to "Age not provided" with ?: if it were null. Finally use with(profile) { } to build and print a
one-line summary reading all three properties through this.
Sample output:
also: profile created for Meera Pillai
Age on file: 29
Meera Pillai from Kochi, verified: false
💡 Hint: apply's block runs with the new UserProfile as this, so displayName = "..."
needs no receiver prefix; the whole apply { } expression still evaluates to that same object.
Exercise 4: Prove the early exit
Scenario: A support tool looks for the first "bulk" order (over ₹5,000) in a list, and the
team wants proof a Sequence really does less work than a List chain for that specific job.
What to do: Build a list of five Orders (reuse Exercise 1's data class) with varied
amounts, at least two of them "bulk." Using a mutable var counter incremented inside each
lambda, run .filter { ... }.map { it.id }.firstOrNull() once as a List chain and once as a
.asSequence() chain, print each counter alongside the id found, then print whether the
sequence's step count was lower.
Sample output:
List: first bulk order id = O-2, steps = 7
Sequence: first bulk order id = O-2, steps = 3
Sequence did fewer steps: true
💡 Hint: count every time a filter or map lambda runs, on both chains, into the SAME
style of counter so the two numbers are directly comparable.
Exercise 5: Cheapest item, and the empty-list trap
Scenario: A price-comparison tool needs the single cheapest item from a catalog, and the
team wants to see for themselves why that function can't safely run on an empty catalog.
What to do: Write data class Item(val name: String, val category: String, val priceInr: Double) and a list of four items across two categories. Use .reduce { acc, item -> ... } to
find the cheapest, print its name and price. Then call the same .reduce { } on
emptyList<Item>() inside a try/catch, printing the caught exception's simple class name.
Finally use .fold(mutableMapOf<String, Int>()) { ... } to count how many items fall in each
category.
Sample output:
Cheapest (reduce): Pen at ₹10.0
reduce on an empty list threw UnsupportedOperationException
Items per category (fold): {Grocery=2, Stationery=2}
💡 Hint: fold's accumulator in the last part is the MutableMap itself — mutate it and
return it as the lambda's last expression each time.
Exercise 6: Department payroll pipeline
Scenario: HR needs the total salary per department, a fast lookup by employee id, and a
split between senior and junior staff by a salary threshold — three different jobs over the same
employee list.
What to do: Write data class Employee(val id: String, val department: String, val salaryInr: Double) and five employees across three departments. Use .groupBy { }.mapValues { } to print total salary per department. Use .associateBy { it.id } to look up one employee's
department by id. Use .partition { it.salaryInr >= 60000.0 } to split into senior and junior
lists and print both, each as a list of ids.
Sample output:
Total salary by department: {Engineering=205000.0, Sales=115000.0, Support=48000.0}
Lookup E3: Engineering
Senior (>= ₹60,000): [E1, E2, E3]
Junior (< ₹60,000): [E4, E5]
💡 Hint: .mapValues { (_, list) -> list.sumOf { it.salaryInr } } turns the grouped
Map<String, List<Employee>> into the Map<String, Double> the output shows.
Exercise 7: UPI top-up with a promo code
Scenario: A wallet top-up flow adds a 5% bonus only for one specific promo code, logs the
result of every request, and must do both without a chain of throwaway variables.
What to do: Write data class TopUpRequest(val amountInr: Double, val promoCode: String?).
Write fun processTopUp(request: TopUpRequest): String using request.run { } as the function
body: inside it, use promoCode?.let { } to compute a 5% bonus only when the code is exactly
"FIRST50" (otherwise 0.0), add it to amountInr, and build a "Credited ₹...(bonus ₹...)" string as the block's result — then chain .also { println("also: $it") } onto the
run before returning. Call processTopUp on three requests: a valid promo, no promo
(null), and an unrecognised promo code.
Sample output:
also: Credited ₹1050.00 (bonus ₹50.00)
also: Credited ₹500.00 (bonus ₹0.00)
also: Credited ₹800.00 (bonus ₹0.00)
💡 Hint: promoCode?.let { code -> if (code == "FIRST50") amountInr * 0.05 else 0.0 } ?: 0.0
handles all three cases (valid code, wrong code, no code) in one expression.
Exercise 8: Delivery payout report
Scenario: A delivery platform wants a payout report per partner, plus a quick check for the
first couple of high-value deliveries, built the same way Part 10's mini-build assembled its
spend report.
What to do: Write data class Delivery(val id: String, val partner: String, val feeInr: Double) and six deliveries across three partners. Using .asSequence(), find the first 2
deliveries with feeInr > 150.0, counting how many were scanned to get there with onEach { }.
Use .fold(0.0) { } for the total of all fees. Use .groupBy { it.partner }.mapValues { },
turned into a sorted List of pairs (highest total first), for a per-partner breakdown. Use
firstOrNull()?.let { } for a headline naming the top earner (or a fallback string if the list
is empty). Assemble the whole report on a StringBuilder with .apply { }, log its line count
with .also { }, and print it.
Sample output:
First 2 deliveries over ₹150: [D2, D3] (scanned 3 of 6)
also: report built, 6 lines
=== Delivery Payout Report ===
Total fees: ₹765.00
Meera earned the most: ₹340.00
Meera: ₹340.00
Ravi: ₹335.00
Kiran: ₹90.00
💡 Hint: the sequence stops scanning as soon as take(2) has what it needs — count only
goes up to 3 out of 6 deliveries, not all of them.
Show the solutions for Part 10 (8 files)
solutions/ex01.kt
data class Order(val id: String, val amountInr: Double)
val ORDERS = listOf(
Order("O-1", 6500.0),
Order("O-2", 150.0),
Order("O-3", 7200.0),
Order("O-4", 80.0)
)
fun isBulk(order: Order) = order.amountInr > 5000.0
fun eligible(orders: List<Order>, rule: (Order) -> Boolean): List<String> =
orders.filter(rule).map { it.id }
fun main() {
println("Bulk orders (function reference): ${eligible(ORDERS, ::isBulk)}")
println("Small orders (trailing lambda): ${eligible(ORDERS) { it.amountInr < 200.0 } }")
}
solutions/ex02.kt
data class Employee(val name: String, val salaryInr: Double)
class SalarySlip(private val bonusInr: Double) {
fun totalInr(e: Employee): Double = e.salaryInr + bonusInr
}
val EMPLOYEES = listOf(
Employee("Kavita Rao", 55000.0),
Employee("Arjun Mehta", 75000.0)
)
fun main() {
// Property reference.
println("Names: ${EMPLOYEES.map(Employee::name)}")
// Bound reference -- `slip` is already baked in.
val slip = SalarySlip(bonusInr = 2000.0)
println("Totals (bound reference): ${EMPLOYEES.map(slip::totalInr)}")
// Unbound reference -- the receiver is the function's own first parameter.
val unbound: (SalarySlip, Employee) -> Double = SalarySlip::totalInr
println("Same total via unbound reference: ${unbound(slip, EMPLOYEES[0])}")
}
solutions/ex03.kt
data class UserProfile(var displayName: String = "", var city: String = "", var isVerified: Boolean = false)
fun main() {
val rawAge: String? = "29"
val profile = UserProfile().apply {
displayName = "Meera Pillai"
city = "Kochi"
}.also { println("also: profile created for ${it.displayName}") }
val ageLine = rawAge?.let { "Age on file: $it" } ?: "Age not provided"
println(ageLine)
val summary = with(profile) { "$displayName from $city, verified: $isVerified" }
println(summary)
}
solutions/ex04.kt
data class Order(val id: String, val amountInr: Double)
val ORDERS = listOf(
Order("O-1", 150.0),
Order("O-2", 6500.0),
Order("O-3", 80.0),
Order("O-4", 7200.0),
Order("O-5", 50.0)
)
fun main() {
var listSteps = 0
val firstBulkList = ORDERS
.filter { listSteps++; it.amountInr > 5000.0 }
.map { listSteps++; it.id }
.firstOrNull()
println("List: first bulk order id = $firstBulkList, steps = $listSteps")
var seqSteps = 0
val firstBulkSeq = ORDERS.asSequence()
.filter { seqSteps++; it.amountInr > 5000.0 }
.map { seqSteps++; it.id }
.firstOrNull()
println("Sequence: first bulk order id = $firstBulkSeq, steps = $seqSteps")
println("Sequence did fewer steps: ${seqSteps < listSteps}")
}
solutions/ex05.kt
data class Item(val name: String, val category: String, val priceInr: Double)
val ITEMS = listOf(
Item("Rice (kg)", "Grocery", 68.0),
Item("Notebook", "Stationery", 45.0),
Item("Toor Dal (kg)", "Grocery", 145.0),
Item("Pen", "Stationery", 10.0)
)
fun main() {
val cheapest = ITEMS.reduce { acc, item -> if (item.priceInr < acc.priceInr) item else acc }
println("Cheapest (reduce): ${cheapest.name} at ₹${cheapest.priceInr}")
try {
emptyList<Item>().reduce { acc, item -> if (item.priceInr < acc.priceInr) item else acc }
} catch (e: UnsupportedOperationException) {
println("reduce on an empty list threw ${e::class.simpleName}")
}
val countByCategory = ITEMS.fold(mutableMapOf<String, Int>()) { acc, item ->
acc[item.category] = (acc[item.category] ?: 0) + 1
acc
}
println("Items per category (fold): $countByCategory")
}
solutions/ex06.kt
data class Employee(val id: String, val department: String, val salaryInr: Double)
val EMPLOYEES = listOf(
Employee("E1", "Engineering", 95000.0),
Employee("E2", "Sales", 60000.0),
Employee("E3", "Engineering", 110000.0),
Employee("E4", "Sales", 55000.0),
Employee("E5", "Support", 48000.0)
)
fun main() {
val totalByDept = EMPLOYEES
.groupBy { it.department }
.mapValues { (_, list) -> list.sumOf { it.salaryInr } }
println("Total salary by department: $totalByDept")
val byId = EMPLOYEES.associateBy { it.id }
println("Lookup E3: ${byId["E3"]?.department}")
val (senior, junior) = EMPLOYEES.partition { it.salaryInr >= 60000.0 }
println("Senior (>= ₹60,000): ${senior.map { it.id }}")
println("Junior (< ₹60,000): ${junior.map { it.id }}")
}
solutions/ex07.kt
data class TopUpRequest(val amountInr: Double, val promoCode: String?)
fun processTopUp(request: TopUpRequest): String = request.run {
val bonus = promoCode?.let { code -> if (code == "FIRST50") amountInr * 0.05 else 0.0 } ?: 0.0
val total = amountInr + bonus
"Credited ₹%.2f (bonus ₹%.2f)".format(total, bonus)
}.also { println("also: $it") }
fun main() {
val requests = listOf(
TopUpRequest(1000.0, promoCode = "FIRST50"),
TopUpRequest(500.0, promoCode = null),
TopUpRequest(800.0, promoCode = "EXPIRED10")
)
requests.forEach { processTopUp(it) }
}
solutions/ex08.kt
data class Delivery(val id: String, val partner: String, val feeInr: Double)
val DELIVERIES = listOf(
Delivery("D1", "Ravi", 60.0),
Delivery("D2", "Meera", 180.0),
Delivery("D3", "Ravi", 220.0),
Delivery("D4", "Kiran", 90.0),
Delivery("D5", "Meera", 160.0),
Delivery("D6", "Ravi", 55.0)
)
fun main() {
var scanned = 0
val firstTwoBig = DELIVERIES.asSequence()
.onEach { scanned++ }
.filter { it.feeInr > 150.0 }
.take(2)
.toList()
println("First 2 deliveries over ₹150: ${firstTwoBig.map { it.id }} (scanned $scanned of ${DELIVERIES.size})")
val totalFees = DELIVERIES.fold(0.0) { acc, d -> acc + d.feeInr }
val byPartner = DELIVERIES
.groupBy { it.partner }
.mapValues { (_, list) -> list.sumOf { it.feeInr } }
.toList()
.sortedByDescending { (_, total) -> total }
val headline = byPartner.firstOrNull()?.let { (partner, total) ->
"$partner earned the most: ₹%.2f".format(total)
} ?: "No deliveries"
val report = StringBuilder().apply {
appendLine("=== Delivery Payout Report ===")
appendLine("Total fees: ₹%.2f".format(totalFees))
appendLine(headline)
byPartner.forEach { (partner, total) -> appendLine(" $partner: ₹%.2f".format(total)) }
}.also { println("also: report built, ${it.lines().size - 1} lines") }
.toString()
print(report)
}
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
| Forgetting a lambda is a value | Treating { it > 100 } as special filter-only syntax instead of something storable in a val with a function type |
Write val rule: (Double) -> Boolean = { it > 100 } once to see it's just a value |
Confusing apply/also (return receiver) with let/run (return block result) |
Chaining breaks, or the wrong value gets assigned, if the pair is swapped | Remember: apply/also hand back what you started with; let/run/with hand back what the block computed |
Assuming .asSequence() always wins |
For small, one-off lists the per-element wrapping has its own overhead with no payoff | Reach for Sequence for long chains or early exits (take/first); a plain List is fine for small, reused data |
Calling .reduce { } on a collection that might be empty |
reduce seeds from the first element and has none to use — throws UnsupportedOperationException |
Use fold(initial) { } instead, which always has initial to fall back on |
Reaching for groupBy when only counts are needed |
Builds a full intermediate List per key before you'd throw it away for a count |
Use groupingBy { }.eachCount() |
Expecting associateBy to keep every match for a duplicate key |
It keeps exactly one value per key — the last match silently overwrites earlier ones | Use groupBy instead when every match matters, not just the latest |
Writing ::SomeClass::member or similar for a member reference without a receiver |
An unbound reference (SomeClass::member) takes the receiver as parameter 1; mixing that up with a bound one causes an arity mismatch |
Bind with an instance (obj::member) or supply the receiver as the first argument to the unbound form |
Quick recap
- A lambda is
{ params -> body }and a genuine value with a function type like(T) -> R; trailing lambda syntax moves the last lambda argument outside the parentheses. - A higher-order function takes and/or returns a function;
::nameis a function reference — bound (tied to an object) or unbound (receiver as the first parameter). let/run/withreturn the block's result;apply/alsoreturn the receiver unchanged;itis used bylet/also,thisbyrun/with/apply.Sequenceevaluation is lazy and element-by-element; nothing runs until a terminal operation, and an early exit liketake()can skip most of the data entirely.foldtakes an explicit seed and can change type;reduceseeds from the first element and throws on an empty collection.groupBykeeps every match per key;associateBykeeps only the last;groupingBy().eachCount()skips the intermediate list when only counts matter;partitionsplits into exactly two lists.
Checklist
- I wrote a lambda as an explicitly-typed
valand called it like a function. - I wrote a function that returns a function, and called the function it returned.
- I used a bound and an unbound function reference, and a property reference.
- I used all five scope functions myself and can say which two return the receiver.
- I proved sequence laziness by printing the step order, not just the step count.
- I triggered
reduce's empty-collection crash and fixed it by switching tofold. - I chained
groupBy→filter→mapValues→sortedByDescendinginto one pipeline. - I built and ran the report pipeline myself, including the early-exit sequence scan.