Part 13 / Stage 3
Generics and advanced typing
Goal: Write one piece of logic that works for many types, safely -- generic classes and functions, variance (
out/in, declaration-site and use-site), bounded type parameters andwhereclauses, type erasure and thereifiedworkaround, and type aliases. Time: ~5 hours · Level: comfortable with Stage 2, especially sealed types/enums and higher-order functions (Part 9, Part 10)
🔍 Going deeper: generics show up constantly from here on -- coroutine builders in the next part (
async<T>,Deferred<T>) are ordinary generic functions and generic classes, nothing more exotic. Getting comfortable with<T>now pays off immediately in Part 14.
What you will learn
- Generic classes and functions:
Crate<T>,Page<T>,fun <T> paginate(...) - Bounded type parameters (
T : Comparable<T>) andwhereclauses for more than one bound - Declaration-site variance:
outfor a type that only producesT,infor one that only consumes it - Use-site variance (
Array<out Any>,Array<in Int>) and star projections (Store<*>) for an unknown type argument - Type erasure -- why
it is Tdoesn't compile for a plain generic -- and theinline fun <reified T>workaround - Type aliases, including aliasing a function type, for readability with no runtime cost
- Building a generic, type-safe in-memory repository that works for any entity type
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 generics, variance, bounded type
parameters/where, reified, and type aliases from this part, on top of everything Stage 1 and
2 covered. No coroutines yet -- those start in Part 14.
Exercise 1: Stock bin
Scenario: a Swadesh Mart warehouse worker needs a generic bin that holds one SKU's stock and
always picks the oldest item first (first in, first out).
What to do: write class StockBin<T> with add(item: T), removeOldest(): T? (returns and
removes the earliest-added item, or null if empty), and a count: Int property. Add three
items, print the count, remove the oldest, print the count again.
Sample output:
Bin has 3 item(s)
Removed oldest: Basmati Rice
Bin has 2 item(s)
💡 Hint: a MutableList<T> backing it with removeAt(0) gives FIFO order for free.
Exercise 2: Smaller of two
Scenario: a pricing tool needs to pick the cheaper of two prices, and separately, the
alphabetically earlier of two product names -- with one function, not two.
What to do: write fun <T : Comparable<T>> smaller(a: T, b: T): T. Call it once with two
Doubles and once with two Strings.
Sample output:
Cheaper price: 180.0
Earlier alphabetically: Dal
💡 Hint: the upper bound T : Comparable<T> is what makes a < b legal inside the function
at all -- without it, this doesn't compile.
Exercise 3: Snack dispenser
Scenario: a vending machine's dispenser only ever hands snacks OUT -- it never needs to take
one back -- so a generic helper that inspects "any dispenser of anything" should be able to
accept it.
What to do: write class Dispenser<out T>(private val stock: List<T>) with a dispense(): T? that returns and advances past the next item (or null once empty). Write fun describeDispenser(d: Dispenser<Any>) that prints the result of calling dispense() on it. Pass
a Dispenser<String> to it directly, then dispense once more from the original.
Sample output:
Next item: Lays
Second dispense: Kurkure
💡 Hint: describeDispenser takes a Dispenser<Any> parameter; passing a Dispenser<String>
straight to it only compiles because of the out on Dispenser's type parameter.
Exercise 4: Order logger
Scenario: a generic logger that can log ANYTHING should also be usable wherever a logger for
one specific type (like String order messages) is expected.
What to do: write interface OrderLogger<in T> { fun log(item: T) }, a class AnyLogger : OrderLogger<Any> that prints "LOG: $item", then assign an AnyLogger instance to a variable
typed OrderLogger<String> and call log on it.
Sample output:
LOG: Order #4821 placed
💡 Hint: this only compiles because OrderLogger<T> declared T as in -- try removing
in and watch the assignment fail.
Exercise 5: Top-rated menu item
Scenario: a food-delivery app needs the highest-rated item on a restaurant's menu, and the
comparison logic should only work for things that are BOTH ratable and comparable.
What to do: write interface HasRating { val rating: Double }, a data class MenuItem(val name: String, override val rating: Double) : HasRating, Comparable<MenuItem> comparing by
rating, and fun <T> topRated(items: List<T>): T where T : HasRating, T : Comparable<T>. Call it
on a list of three MenuItems.
Sample output:
Top rated: Paneer Butter Masala (4.6)
💡 Hint: where T : HasRating, T : Comparable<T> is required here -- <T : HasRating, Comparable<T>> in the angle brackets is not valid syntax for two bounds on the same T.
Exercise 6: Count by type
Scenario: a shopping cart stores mixed data (Any), and the checkout screen needs to count
how many items are of each underlying type before formatting them differently.
What to do: write inline fun <reified T> List<Any>.countOfType(): Int using count { it is T }. Call it three times on the same mixed list, once per type.
Sample output:
Strings in cart: 4
Doubles in cart: 2
Ints in cart: 1
💡 Hint: without reified (and inline), it is T does not compile -- type erasure means
there's no T left at runtime to check against.
Exercise 7: Retry with a named callback type
Scenario: a flaky payment-confirmation step needs to be retried a fixed number of times, and
the retry function's lambda parameter type is repeated enough that it deserves its own name.
What to do: write typealias Attempt = (attemptNumber: Int) -> Boolean and fun retryUntil(maxAttempts: Int, attempt: Attempt): Boolean that calls attempt for 1..maxAttempts,
returning true on the first success and printing a retry message on each failure. Call it with
a lambda that only succeeds on attempt 3, tracking how many times it was actually called.
Sample output:
attempt 1 failed, retrying...
attempt 2 failed, retrying...
Succeeded: true after 3 attempt(s)
💡 Hint: the alias doesn't change what the type IS -- attempt: (Int) -> Boolean would work
identically -- it only changes how readable the signature is.
Exercise 8: Repository with a filter and a cross-type total
Scenario: the generic repository from Section 7 needs a way to search within one entity
type, plus a way to report a grand total across several DIFFERENT repositories (products AND
customers) without caring what each one actually stores.
What to do: extend Repository<ID, T>/InMemoryRepository<ID, T> with findAllMatching(predicate: (T) -> Boolean): List<T>. Then write fun totalEntities(repositories: List<Repository<*, *>>): Int that sums each repository's count. Build a Product repository and a Customer
repository, filter the products under ₹300, and total both repositories together.
Sample output:
Affordable products: [Toor Dal, Sunflower Oil]
Total entities across both repositories: 4
💡 Hint: Repository<*, *> is a star projection on BOTH type parameters -- totalEntities
can call .count (doesn't mention ID or T) but could not call findById on it.
Show the solutions for Part 13 (8 files)
solutions/ex01.kt
class StockBin<T> {
private val items = mutableListOf<T>()
fun add(item: T) {
items.add(item)
}
fun removeOldest(): T? = if (items.isEmpty()) null else items.removeAt(0)
val count: Int get() = items.size
}
fun main() {
val bin = StockBin<String>()
bin.add("Basmati Rice")
bin.add("Toor Dal")
bin.add("Sunflower Oil")
println("Bin has ${bin.count} item(s)")
println("Removed oldest: ${bin.removeOldest()}")
println("Bin has ${bin.count} item(s)")
}
solutions/ex02.kt
fun <T : Comparable<T>> smaller(a: T, b: T): T = if (a < b) a else b
fun main() {
println("Cheaper price: ${smaller(420.0, 180.0)}")
println("Earlier alphabetically: ${smaller("Rice", "Dal")}")
}
solutions/ex03.kt
class Dispenser<out T>(private val stock: List<T>) {
private var next = 0
fun dispense(): T? = stock.getOrNull(next)?.also { next++ }
}
fun describeDispenser(d: Dispenser<Any>) {
println("Next item: ${d.dispense()}")
}
fun main() {
val snackDispenser: Dispenser<String> = Dispenser(listOf("Lays", "Kurkure", "Bingo"))
describeDispenser(snackDispenser) // Dispenser<String> accepted as Dispenser<Any>, because of `out`
println("Second dispense: ${snackDispenser.dispense()}")
}
solutions/ex04.kt
interface OrderLogger<in T> {
fun log(item: T)
}
class AnyLogger : OrderLogger<Any> {
override fun log(item: Any) = println("LOG: $item")
}
fun main() {
val anyLogger = AnyLogger()
val orderLogger: OrderLogger<String> = anyLogger // allowed because of `in`
orderLogger.log("Order #4821 placed")
}
solutions/ex05.kt
interface HasRating {
val rating: Double
}
data class MenuItem(val name: String, override val rating: Double) : HasRating, Comparable<MenuItem> {
override fun compareTo(other: MenuItem): Int = rating.compareTo(other.rating)
}
fun <T> topRated(items: List<T>): T where T : HasRating, T : Comparable<T> =
items.maxOrNull() ?: throw NoSuchElementException("items must not be empty")
fun main() {
val items = listOf(
MenuItem("Masala Dosa", 4.3),
MenuItem("Paneer Butter Masala", 4.6),
MenuItem("Veg Biryani", 4.1),
)
val best = topRated(items)
println("Top rated: ${best.name} (${best.rating})")
}
solutions/ex06.kt
inline fun <reified T> List<Any>.countOfType(): Int = count { it is T }
fun main() {
val cart: List<Any> = listOf("Rice", 199.0, "Dal", 45.0, "Oil", 320, "Sugar")
println("Strings in cart: ${cart.countOfType<String>()}")
println("Doubles in cart: ${cart.countOfType<Double>()}")
println("Ints in cart: ${cart.countOfType<Int>()}")
}
solutions/ex07.kt
// Before this alias, retryUntil's second parameter type would have to be spelled out in full,
// here and at every call site: (Int) -> Boolean.
typealias Attempt = (attemptNumber: Int) -> Boolean
fun retryUntil(maxAttempts: Int, attempt: Attempt): Boolean {
for (n in 1..maxAttempts) {
if (attempt(n)) return true
println(" attempt $n failed, retrying...")
}
return false
}
fun main() {
var callCount = 0
val success = retryUntil(maxAttempts = 3) { n ->
callCount++
n == 3 // succeed on the third try
}
println("Succeeded: $success after $callCount attempt(s)")
}
solutions/ex08.kt
interface Repository<ID, T> {
fun save(entity: T): T
fun findAll(): List<T>
fun findAllMatching(predicate: (T) -> Boolean): List<T>
val count: Int
}
class InMemoryRepository<ID, T>(private val idOf: (T) -> ID) : Repository<ID, T> {
private val store = linkedMapOf<ID, T>()
override fun save(entity: T): T {
store[idOf(entity)] = entity
return entity
}
override fun findAll(): List<T> = store.values.toList()
override fun findAllMatching(predicate: (T) -> Boolean): List<T> = store.values.filter(predicate)
override val count: Int get() = store.size
}
data class Product(val id: String, val name: String, val priceInRupees: Double)
data class Customer(val id: String, val name: String)
// Star projection: we only need `count` here, which doesn't depend on ID or T.
fun totalEntities(repositories: List<Repository<*, *>>): Int = repositories.sumOf { it.count }
fun main() {
val products: Repository<String, Product> = InMemoryRepository { it.id }
products.save(Product("P-01", "Basmati Rice", 420.0))
products.save(Product("P-02", "Toor Dal", 180.0))
products.save(Product("P-03", "Sunflower Oil", 210.0))
val affordable = products.findAllMatching { it.priceInRupees < 300.0 }
println("Affordable products: ${affordable.map { it.name }}")
val customers: Repository<String, Customer> = InMemoryRepository { it.id }
customers.save(Customer("C-01", "Asha Kulkarni"))
println("Total entities across both repositories: ${totalEntities(listOf(products, customers))}")
}
Common mistakes
| Mistake | Why it is wrong | Fix |
|---|---|---|
Writing fun <T> max(a: T, b: T): T = if (a > b) a else b with no bound |
T has no guaranteed compareTo; a > b doesn't compile |
Add T : Comparable<T> as an upper bound |
Writing T : X, T : Y in the angle brackets |
Only one bound fits after the colon | Use a where clause: where T : X, T : Y |
Marking a class out T and then adding a method that takes a T parameter |
out means "producer only" -- the compiler rejects any method that would let you put a T in |
Drop out (go invariant) or keep the type purely a producer |
it is T inside a plain generic function |
Type erasure: T doesn't exist at runtime, only at compile time |
Make the function inline with a reified T, if it can be inlined at every call site |
@Suppress("UNCHECKED_CAST") as a shortcut instead of reified |
Compiles and "works", but performs no real check -- wrong data flows through silently | Reach for inline fun <reified T> first; only use an unchecked cast when you've independently proven the type is correct |
Treating a typealias as a new type |
ProductId is still exactly a String at runtime -- nothing stops you passing a random String where a ProductId is expected |
Use a typealias purely for readability; reach for a real wrapper class (Stage 2, Part 9) if you need the compiler to actually stop mixups |
Expecting List<String> to NOT be assignable to List<Any> |
The standard library already declares List<out T> -- this assignment is fine and the point of covariance |
Only worry about variance for your OWN generic classes/interfaces, which are invariant unless you say out/in |
Quick recap
- A generic class/function takes a type parameter in
<T>, so one definition works for many types, with full compile-time type checking per instantiation. - An upper bound (
T : Comparable<T>) lets you use operations that bound guarantees;wherelists more than one bound on the sameT. - Declaration-site
out(producer-only, covariant) andin(consumer-only, contravariant) let your own generic types participate in subtyping the wayList<out T>already does. - Use-site variance (
Array<out Any>,Array<in Int>) appliesout/into one parameter's type instead of the whole class; a star projection (Store<*>) says "some type, don't care which" for members that don't touch the type parameter. - Type erasure means
Tdoesn't exist at runtime inside a plain generic function;inline fun <reified T>is the one legal way around it. - A
typealiasis a readability-only second name for a type (including a function type) -- no new type, no runtime cost, no extra type safety. - A generic
Repository<ID, T>is the same pattern as every section before it, combined: one implementation, many unrelated entity types, each one fully type-checked.
Checklist
- I wrote a generic class and a generic function, and used each with at least two different type arguments.
- I wrote a function with an upper bound, and a separate one with a
whereclause needing two bounds. - I declared one covariant (
out) type and one contravariant (in) type, and explained why each direction is safe. - I used use-site variance on an
Arrayparameter, and a star projection on a generic parameter whose exact type argument I didn't need. - I hit the "Cannot check for instance of erased type" error myself, then fixed it with
inline fun <reified T>. - I wrote a
typealiasfor a type and for a function type, and used both at a call site. - I built and ran the generic repository, including a lookup that returns
null.