Explain it simply
Explain it simply
This lesson also introduces nothing new. It joins classes, inheritance, data classes, collections and lambdas into three bigger tasks that are closer to what a small real program does. As with the fundamentals set, write your own version first and use the reference solution only to compare.
Imagine running a tiny shop and a tiny zoo at the same time. The zoo shows how one list of different animals can be treated alike, because each animal knows its own sound. The shop shows how a list of products can be filtered, ranked and discounted without touching the original stock list: every step hands you a new list, and the original stays as it was.
Problem → Why → Solution
The problem: four walls a first draft hits
A typical first draft of these tasks runs into four walls. Animal("Rex") does not compile, because an abstract class cannot be instantiated. product.price = newPrice does not compile either, because price is a val. Calling sortedByDescending as a statement compiles and silently does nothing, because it returns a new list that nobody keeps. And averaging an empty list prints NaN, not 0.
The first two walls are compiler errors, the friendly kind that stop you before the program runs: cannot create an instance of an abstract class, and 'val' cannot be reassigned. The last two compile, run and print something, so you only notice them if you read the output closely.
abstract class Animal(val name: String) {
abstract fun sound(): String
}
data class Product(val name: String, val price: Double)
fun main() {
val pet = Animal("Rex") // error: abstract class
val laptop = Product("Laptop", 1_500_000.0)
laptop.price = 1_350_000.0 // error: val
val products = listOf(Product("Pen", 500.0), Product("Laptop", 1_500_000.0))
products.sortedByDescending { it.price } // result thrown away
println(products.map { it.name }) // [Pen, Laptop], not sorted
println(emptyList<Double>().average()) // NaN, not 0
}Why do two of them run without complaint?
sortedByDescending, map and filter never change the list they are called on; each returns a new list. If you ignore the return value, the call is legal but pointless. average() on an empty collection divides zero by zero, which for Double is NaN rather than an exception. Neither is a type error, so the compiler cannot help: you have to think about the empty case and use the returned value.
Core concept: one idea per task, plus one habit
The three tasks each isolate one idea from the intermediate and advanced chapters. A fourth point cuts across all three: every function needs an answer for no data. Read these four notes before you write code, then compare your own functions with the reference solution.
Task 1: abstract class plus override
abstract class Animal(val name: String) holds what every animal shares and declares abstract fun sound(), which has no body. A subclass such as Dog(name: String) : Animal(name) must override sound(), and the compiler refuses it otherwise. Because a Dog is an Animal, a List<Animal> can hold dogs and cats together, and animal.sound() runs each object's own version. That is polymorphism: the loop never asks which kind it has, and describe() is written once in the base class for every subclass to reuse.
Task 2: filter, sort and group a list of data
filter keeps elements, map transforms them and sortedWith orders them, and all three return a new list. When two prices are equal, sorting by price alone keeps them in their input order, which changes whenever the input does; adding thenBy { it.name } states the tie-break outright. groupBy { it.category } returns a Map, and indexing a map with a key that does not exist gives null, so orEmpty() turns a missing category into an empty list.
Task 3: a higher-order function that copies
applyDiscount takes discountFn: (Double) -> Double, so the caller decides the rule: a 10 percent cut, a flat reduction, anything. map applies it to every product and copy(price = ...) builds a new Product with the new price while the original stays untouched. coerceAtLeast(0.0) guards against a rule that would push a price below zero, and an empty list simply maps to an empty list.
Habit: say what empty and missing mean
Every function here has an answer for no data: chorus() prints (silence), averagePrice() returns null instead of NaN, and byCategory["Toys"].orEmpty() gives an empty list. Decide those answers when you write the function, not after a customer finds the crash.
| Tool | Returns | Where it surprises you |
|---|---|---|
| filter, map, sortedBy | A new list | Ignoring the result does nothing |
| copy() | A new data class instance | The original keeps its old values |
| map[key] | The value or null | A missing key gives null, not an error |
| average() | A Double | NaN for an empty collection |
| maxByOrNull | The element or null | Null for empty, the first wins a tie |
- Model with classes and hierarchy
- Transform with filter, map, sort
- Return new objects, keep the input
- Decide what empty and missing mean
Each step in a collection pipeline produces something new; nothing earlier in the chain is edited.
General pattern
abstract class Base(val name: String) {
abstract fun act(): String
}
class Child(name: String) : Base(name) {
override fun act() = "..."
}
val ranked = items.filter { it.size > 3 }.sortedByDescending { it.size }
val changed = items.map { it.copy(size = rule(it.size)) }
val group = byKind["missing"].orEmpty()An abstract base declares what subclasses must do, collection functions return new lists, copy() builds changed duplicates, and orEmpty() turns a missing lookup into an empty list.
Reference answer: three tasks with their edge cases
Each task is a small function that main exercises with normal data and at least one edge case: an empty list, a tie, a missing category or an oversized discount. Money is stored as Double here only to keep the exercise short, and production code would use BigDecimal or whole minor units. Every number printed below comes from actually running this program.
abstract class Animal(val name: String) {
abstract fun sound(): String
fun describe(): String = "$name says ${sound()}"
}
class Dog(name: String) : Animal(name) {
override fun sound() = "Woof"
}
class Cat(name: String) : Animal(name) {
override fun sound() = "Meow"
}
data class Product(val name: String, val price: Double, val category: String)
fun chorus(animals: List<Animal>): String =
if (animals.isEmpty()) "(silence)" else animals.joinToString(" / ") { it.describe() }
fun rankByPrice(products: List<Product>): List<Product> =
products.sortedWith(compareByDescending<Product> { it.price }.thenBy { it.name })
fun averagePrice(products: List<Product>): Double? =
if (products.isEmpty()) null else products.map { it.price }.average()
fun applyDiscount(
products: List<Product>,
discountFn: (Double) -> Double,
): List<Product> =
products.map { it.copy(price = discountFn(it.price).coerceAtLeast(0.0)) }
fun main() {
val animals: List<Animal> = listOf(Dog("Rex"), Cat("Mimi"))
println("Task 1: " + chorus(animals))
println("Task 1 (empty): " + chorus(emptyList()))
val products = listOf(
Product("Laptop", 1_500_000.0, "Electronics"),
Product("Mouse", 25_000.0, "Electronics"),
Product("Book", 8_000.0, "Stationery"),
Product("Phone", 1_200_000.0, "Electronics"),
Product("Keyboard", 25_000.0, "Electronics"),
Product("Pen", 500.0, "Stationery"),
)
val expensive = products.filter { it.price > 1_000_000 }.map { it.name }
println("Task 2 expensive: $expensive")
println("Task 2 ranked: ${rankByPrice(products).map { it.name }}")
val byCategory = products.groupBy { it.category }
val stationery = byCategory["Stationery"].orEmpty()
val toys = byCategory["Toys"].orEmpty()
println("Task 2 categories: Stationery=${stationery.size}, Toys=${toys.size}")
val average = averagePrice(products)
println("Task 2 average: $average, empty: ${averagePrice(emptyList())}")
val discounted = applyDiscount(products) { price -> price * 0.9 }
println("Task 3 discounted: ${discounted.map { it.price }}")
println("Task 3 original untouched: ${products.first().price}")
val clamped = applyDiscount(products) { price -> price - 50_000.0 }
println("Task 3 oversized discount: ${clamped.map { it.price }}")
println("Task 3 empty: ${applyDiscount(emptyList()) { it * 0.5 }}")
}Code breakdown
- Abstract member
abstract fun sound(): StringThere is no body here: every concrete subclass must supply one. Animal("Rex") would not compile, but Dog("Rex") does, and describe() in the base class calls whichever sound() the real object has.
- Override in a subclass
override fun sound() = "Woof"override is mandatory, and the return type String is inferred from the literal. Cat does the same with Meow, so the list prints each animal's own sound.
- Explicit tie-break
products.sortedWith(compareByDescending<Product> { it.price }.thenBy { it.name })Mouse and Keyboard both cost 25000.0. thenBy puts Keyboard before Mouse alphabetically, which makes the ranked output predictable and independent of the input order.
- Null instead of NaN
if (products.isEmpty()) null else products.map { it.price }.average()average() of an empty collection is NaN, which then spreads through later arithmetic. Returning Double? makes the empty case explicit: the average is 459750.0 for six products and null for none.
- A rule parameter that returns copies
products.map { it.copy(price = discountFn(it.price).coerceAtLeast(0.0)) }discountFn decides the new price, coerceAtLeast(0.0) stops it from going negative, and copy builds new Product objects. The original list is untouched, which the original untouched line proves.
- A missing key
val toys = byCategory["Toys"].orEmpty()groupBy only creates keys that occur, so no category called Toys exists. The lookup returns null and orEmpty() turns it into an empty list whose size is 0.
Task 1: Rex says Woof / Mimi says Meow
Task 1 (empty): (silence)
Task 2 expensive: [Laptop, Phone]
Task 2 ranked: [Laptop, Phone, Keyboard, Mouse, Book, Pen]
Task 2 categories: Stationery=2, Toys=0
Task 2 average: 459750.0, empty: null
Task 3 discounted: [1350000.0, 22500.0, 7200.0, 1080000.0, 22500.0, 450.0]
Task 3 original untouched: 1500000.0
Task 3 oversized discount: [1450000.0, 0.0, 0.0, 1150000.0, 0.0, 0.0]
Task 3 empty: []copy(), map and sorting never edit the original
The most common collection surprises are all about identity: which list or object is the new one? Run the snippet and read its four lines in order.
data class Product(val name: String, val price: Double)
fun main() {
val original = listOf(Product("Pen", 500.0), Product("Book", 8000.0))
val halfPrice = original.map { it.copy(price = it.price * 0.5) }
println(original.map { it.price })
println(halfPrice.map { it.price })
val ranked = original.sortedByDescending { it.price }
println(ranked.map { it.name })
println(original.map { it.name })
}halfPrice holds new Product objects with halved prices, while original still prints 500.0 and 8000.0. ranked is a new list sorted by price, and original keeps its input order. If you really want the original list to change, you need a MutableList and an in-place call such as sortByDescending, which is a different function from sortedByDescending.
Abstract class or interface?
Animal could also have been an interface. The choice depends on what the types share, and the table below is the short version of the decision.
| Question | Abstract class | Interface |
|---|---|---|
| Can it keep state in a constructor? | Yes, as in Animal(val name: String) | No constructor and no backing fields |
| How many can a class use? | Extend only one | Implement as many as needed |
| Typical use | A common base with shared code | A capability such as Reportable |
In real projects
In real projects
Class hierarchies with an abstract base are common wherever one list holds many kinds of thing: shapes in a drawing program, payment methods at a checkout, notification channels in a server. The code that loops over the list stays the same when a new subclass appears, which is the whole point of the Animal task. In modern Kotlin you will also see sealed classes and interfaces chosen for this job when the set of subclasses is closed.
The Product tasks mirror reporting code: filter the orders, group by category, sort by value and format the result. Production code would store money as BigDecimal or as whole units of the smallest currency, not as Double, because a Double cannot represent an amount like 0.1 exactly. Immutable copies are also what make such pipelines safe in concurrent programs, where two threads can read the same product list without either being able to change it.
Common mistakes
Common mistakes
Trying to instantiate an abstract class
Animal("X") fails with: cannot create an instance of an abstract class. Create a concrete subclass such as Dog, or declare a List<Animal> and fill it with subclass instances.
Assigning to a data class property
product.price = newPrice fails with: 'val' cannot be reassigned. Build a changed copy with product.copy(price = newPrice) and store that copy where you need it.
Ignoring the result of sortedByDescending, map or filter
These functions return new lists. Writing products.sortedByDescending { it.price } on its own line leaves products unchanged, and printing products afterwards still shows the old order. Assign the result to a val, or use the in-place sortByDescending on a MutableList.
Averaging or taking the maximum of an empty list unchecked
average() on an empty collection gives NaN, and maxOf throws NoSuchElementException on an empty collection, while maxByOrNull returns null. Pick the null-returning version or check isEmpty() first.
Mini challenge
Shapes, rankings and a pluggable top-N
Practise the same ideas on a new domain. Build an abstract Shape class with two subclasses, then write largest(shapes) that returns null for an empty list, areaByKind(shapes) that sums areas per shape name, and topN(shapes, n, selector) that takes a function as its ranking rule. Test empty lists, ties, and an n that is too large or negative.
- Shape is abstract with an abstract area(), and Rectangle and Triangle override it
- largest() returns Shape? and is null for an empty list; the first shape wins a tie
- areaByKind() returns a Map<String, Double> and an empty map for an empty list
- topN() takes selector: (Shape) -> Double, breaks ties by name and never throws for n <= 0 or n > size
abstract class Shape(val name: String) {
// TODO: abstract fun area(): Double, and a toString() such as Rectangle(12.0)
}
class Rectangle(/* width, height */) : Shape("Rectangle") {
// TODO: override area()
}
class Triangle(/* base, height */) : Shape("Triangle") {
// TODO: override area()
}
fun largest(shapes: List<Shape>): Shape? {
// TODO: null for an empty list, the first shape wins a tie
}
fun areaByKind(shapes: List<Shape>): Map<String, Double> {
// TODO: group by name and sum the areas
}
fun topN(shapes: List<Shape>, n: Int, selector: (Shape) -> Double): List<Shape> {
// TODO: sort by selector descending, then by name; guard n <= 0
}
fun main() {
// TODO: four shapes (include a tie), then test empty lists and n = 2, 10, -3
}Expected: largest prints Rectangle(12.0) and null for none, areaByKind prints Rectangle=16.0 and Triangle=17.0 and an empty map for none, topN with two lists Rectangle(12.0) and Triangle(12.0), n = 10 returns all four shapes, n = -3 returns an empty list, and the reversed selector lists the two smallest shapes.
Show hint
maxByOrNull { it.area() } returns null for an empty list. groupBy { it.name } followed by mapValues { (_, group) -> group.sumOf { it.area() } } gives the sums. For topN use sortedWith(compareByDescending<Shape> { selector(it) }.thenBy { it.name }) and take(n.coerceAtLeast(0)).
Show solution
abstract class Shape(val name: String) {
abstract fun area(): Double
override fun toString() = "$name(${area()})"
}
class Rectangle(private val width: Double, private val height: Double) :
Shape("Rectangle") {
override fun area() = width * height
}
class Triangle(private val base: Double, private val height: Double) : Shape("Triangle") {
override fun area() = base * height / 2
}
fun largest(shapes: List<Shape>): Shape? = shapes.maxByOrNull { it.area() }
fun areaByKind(shapes: List<Shape>): Map<String, Double> =
shapes.groupBy { it.name }.mapValues { (_, group) -> group.sumOf { it.area() } }
fun topN(shapes: List<Shape>, n: Int, selector: (Shape) -> Double): List<Shape> =
shapes.sortedWith(compareByDescending<Shape> { selector(it) }.thenBy { it.name })
.take(n.coerceAtLeast(0))
fun main() {
val shapes = listOf(
Rectangle(3.0, 4.0),
Triangle(6.0, 4.0),
Rectangle(2.0, 2.0),
Triangle(10.0, 1.0),
)
println("largest: ${largest(shapes)}")
println("largest of none: ${largest(emptyList())}")
println("area by kind: ${areaByKind(shapes)}")
println("area of none: ${areaByKind(emptyList())}")
println("top 2 by area: ${topN(shapes, 2) { it.area() }}")
println("top 10 by area: ${topN(shapes, 10) { it.area() }.size} shapes")
println("top -3 by area: ${topN(shapes, -3) { it.area() }}")
println("smallest first: ${topN(shapes, 2) { -it.area() }}")
}Quick quiz 1 / 3
Quick quiz 2 / 3
Quick quiz 3 / 3
What to remember
- An abstract class holds shared state and declares abstract members, each subclass must override them, and one List<Animal> can hold every subclass
- filter, map and sortedBy return new lists, so use the result, and add thenBy when ties must be predictable
- copy() on a data class makes a changed duplicate, so a higher-order function can transform products without editing the originals
- Decide what empty and missing mean: orEmpty() for map lookups, and null instead of NaN for averages
Kotlin language guide — Kotlin