1. Introduction
When we say “subtyping”, we usually think of inheritance: one type extends another. And in normal (non-generic) life everything is fairly linear: if Expense inherits from Transaction, then a variable of type Transaction can hold a reference to an Expense. This is the basis of polymorphism: “you can substitute a derived class where a base class is expected”.
Let’s lock this in with a small code fragment from our hypothetical finance tracking app (let’s call it BudgetTracker). Here a transaction is the base type, and an expense is a specific kind of transaction:
open class Transaction(val amount: Int, val comment: String)
class Expense(amount: Int, comment: String, val category: String) :
Transaction(amount, comment)
fun main() {
val t: Transaction = Expense(500, "Coffee and croissant", "Food")
println(t.comment) // Coffee and croissant
}
This looks logical: an expense is a transaction, so a “transaction” variable can reference it. And right here it’s easy to take the next “intuitive step”… which will turn out not to be always correct once angle brackets show up.
2. Why Box<Expense> is not Box<Transaction>
As soon as we take a type T and start wrapping it in a generic container Box<T>, we get a new entity: not T, but a “box of T”. And here Kotlin, by default, takes the most cautious position: generic types are invariant by default, meaning “we do not promise any automatic substitution based on inheritance”.
Let’s make the simplest “box”:
class Box<T>(var value: T)
open class Transaction(val amount: Int)
class Expense(amount: Int) : Transaction(amount)
fun main() {
val expenseBox: Box<Expense> = Box(Expense(100))
// This is not allowed (and it’s not a whim):
val txBox: Box<Transaction> = expenseBox
}
At the human level you want to say: “Well, Expense is a subclass of Transaction, so a box of expenses is a box of transactions.” But the compiler disagrees. And it’s not being picky: it proactively prevents a situation where, through a “box of transactions”, we could suddenly put something inside that is not an expense but something else (for example, income) and break the assumption that the inside is exactly Expense.
At this point it’s useful to remember a short thought: subtyping of elements does not have to carry over to subtyping of containers. Next we’ll see why Kotlin makes a pleasant exception for List—but not for MutableList.
3. Why List<Expense> can be used as List<Transaction>
Now comes an important point that is often confused in Kotlin: List is not “just a list”, it is a read-only interface. It provides read operations: get the size, access an element by index, iterate in a loop, but it does not provide “add” or “remove”. Kotlin standardly separates collections into read-only and mutable interfaces: there is an interface for reading and a separate interface for reading+writing.
And here is the key: read-only collections in Kotlin are covariant, meaning List<Rectangle> can be used where List<Shape> is expected if Rectangle inherits from Shape. In plain terms: “if the list is read-only, then a list of more specific elements can be treated as a list of more general ones.”
Let’s apply this to our transactions:
open class Transaction(val amount: Int, val comment: String)
class Expense(amount: Int, comment: String) : Transaction(amount, comment)
fun main() {
val expenses: List<Expense> = listOf(
Expense(120, "Coffee"),
Expense(350, "Taxi")
)
val transactions: List<Transaction> = expenses
println(transactions[0].comment) // Coffee
}
Why is this safe? Because through the variable transactions you cannot do transactions.add(...)—List simply does not have such an operation. That is, you cannot “mix in” some other transaction into the original expenses list. You can only read what is already there.
To reinforce it, it’s useful to compare the contracts:
| Type | Can read elements | Can add/remove |
|---|---|---|
|
yes | no |
|
yes | yes |
And it is precisely because of this read-only interface that Kotlin allows you to “lift” the type up the hierarchy for List.
Important: read-only is not the same as “immutable forever”. List does not promise that the data will never change somewhere else; it promises that through this particular reference type you will not be able to mutate the collection. Kotlin describes exactly this read-only vs mutable interface model.
4. Why MutableList<Expense> cannot be used as MutableList<Transaction>
Now we’re approaching the most “painful” part: why the compiler forbids what seems so logical. It all comes down to one thing: MutableList allows writing.
Imagine Kotlin allowed this line:
open class Transaction(val amount: Int)
class Expense(amount: Int) : Transaction(amount)
class Income(amount: Int) : Transaction(amount)
fun main() {
val expenses: MutableList<Expense> = mutableListOf(Expense(100))
// If this were allowed...
val txs: MutableList<Transaction> = expenses
txs.add(Income(5000)) // added income “to the list of transactions”
// ...then expenses would now contain an Income, and that breaks the type!
}
If the variable txs is a “list of transactions”, then by its contract adding Income(...) is perfectly legal. But if under the hood it’s the same object as expenses (a list of expenses), then we have just quietly mixed income into the expenses list. This becomes a violation of type safety: MutableList<Expense> is no longer a “real list of Expense”.
That’s exactly why Kotlin enforces a strict rule: mutable collections are not covariant, otherwise it would lead to runtime problems and type violations.
In practice you will see an error with roughly this meaning (the text may differ slightly, but the idea is the same):
Type mismatch: Required `MutableList<Transaction>`, found `MutableList<Expense>`
And this is exactly the case where the compiler is not “getting in the way”, but truly preventing a future data breakage.
5. Mental model: “give-out” vs “intake”
To avoid memorizing everything like a spell, it helps to keep a simple everyday analogy in mind. Imagine there is a warehouse, and you came to the service window. In one case you are allowed only to receive goods (“give-out”), in another—only to accept goods (“intake”), and in the third—both receive and accept (and then things get fun, because someone will inevitably bring the wrong thing).
Read-only List is almost “give-out”: you take elements and read them. Therefore a “warehouse of expenses” can be treated as a “warehouse of transactions”: any expense is a transaction, so reading them as transactions is safe.
MutableList is “both give-out and intake at the same time”: you can both take an element and put a new one. And here type substitution becomes dangerous: if you are given an “intake for transactions”, you can bring income there, but if it was actually an “intake for expenses”, chaos follows.
A small diagram to make your brain latch onto it:
flowchart LR
A["List⟨Expense⟩
(read-only)"] --> B["List⟨Transaction⟩
(read-only)"]
C["MutableList⟨Expense⟩
(read+write)"] -.-x D["MutableList⟨Transaction⟩ (read+write)"]
A solid arrow means “safe to substitute”, a dotted arrow with an X means “dangerous, therefore forbidden”.
6. Practice in BudgetTracker: how to accept the “right” lists
In real code, the pain from MutableList<Expense> usually appears not in abstract examples, but when you write a useful function and want to “just accept a list”. For example: compute a sum, print to the console, find a maximum, sort, group.
And here is the main practical advice that follows directly from the Kotlin model: if a function does not have to change the collection, accept List, not MutableList. This immediately makes your API more flexible, and you automatically get that same type “lifting”.
Let’s implement in our app a base type and two operations: printing and summing. Neither mutates the list.
open class Transaction(val amount: Int, val comment: String)
class Expense(amount: Int, comment: String) : Transaction(amount, comment)
fun printTransactions(items: List<Transaction>) {
for (t in items) {
println("${t.amount} — ${t.comment}")
}
}
fun main() {
val expenses: List<Expense> = listOf(
Expense(120, "Coffee"),
Expense(350, "Taxi")
)
printTransactions(expenses)
// 120 — Coffee
// 350 — Taxi
}
Notice the “magic without magic”: printTransactions expects List<Transaction>, and we passed List<Expense>, and everything is fine—because List is read-only and covariant.
Now an example of a function that wants to mutate the list—for example, add a transaction. Here you can no longer “just accept anything”:
open class Transaction(val amount: Int, val comment: String)
class Expense(amount: Int, comment: String) : Transaction(amount, comment)
fun addTestTransaction(storage: MutableList<Transaction>) {
storage.add(Expense(10, "Test expense"))
}
fun main() {
val txs: MutableList<Transaction> = mutableListOf()
addTestTransaction(txs)
println(txs.size) // 1
}
And here is an important observation: if you have a MutableList<Expense> stored somewhere, you will not be able to pass it into addTestTransaction, because it would be potentially unsafe (we already discussed why).
One temporary “survival tactic”, while we are not yet studying special tools of the type system (we are not touching them today), is to make a copy when you need to “mutate temporarily”:
open class Transaction(val amount: Int)
class Expense(amount: Int) : Transaction(amount)
fun addSomething(storage: MutableList<Transaction>) {
storage.add(Expense(999))
}
fun main() {
val expensesOnly: List<Expense> = listOf(Expense(100))
val copyAsTransactions: MutableList<Transaction> = expensesOnly.toMutableList()
addSomething(copyAsTransactions)
println(copyAsTransactions.size) // 2
}
Yes, this is copying. Yes, it costs memory and time. But it is honest: we do not break the original list expensesOnly, and we work with a separate mutable copy. This is a normal “bridge” while you are not yet armed with more precise type contracts.
How to read compiler messages about List and MutableList
Compiler messages in these places are usually short, but annoying. And the main newbie problem is that they perceive them as an “incomprehensible prohibition” rather than as a hint about what exactly could go wrong.
If you see that List<Expense> does not fit List<Transaction>, then most likely you are actually using not List but a mutable type somewhere (or you are expecting it). In Kotlin, read-only collections are covariant, and mutable ones are not. So the first thing to do is to check the function signature: do you really need MutableList there?
If the message says it requires MutableList<Transaction> and you have MutableList<Expense>, it almost always means: “I see you want to write into the collection, and that is unsafe with this substitution.” Then you have a choice: either change the design so the function accepts List and does not mutate; or store the data differently; or explicitly copy the collection into a more general type, as we showed above.
And separately, it’s useful to remember: Kotlin clearly separates read-only and mutable collection interfaces. Sometimes it’s enough to change MutableList to List in a function parameter—and half of the “weird” problems suddenly disappear.
7. Function analogy: why (Transaction) -> String fits (Expense) -> String
There is one more interesting piece that helps your brain get used to the idea that “substitution does not always work the way it seems”. This is function types.
In Kotlin, a function is also a value, and it has a type of the form (A) -> B: it takes A, returns B. A very logical idea works here: if a function can accept any transaction, then it can definitely accept an expense too (because an expense is a special case of a transaction).
From the type perspective this looks “backwards” compared to lists: by its input parameter, a function behaves as if it “allows substitution in the other direction”.
open class Transaction(val comment: String)
class Expense(comment: String) : Transaction(comment)
fun main() {
val formatTransaction: (Transaction) -> String = { t ->
"TX: ${t.comment}"
}
val formatExpense: (Expense) -> String = formatTransaction
println(formatExpense(Expense("Coffee"))) // TX: Coffee
}
Why is this safe? Because formatTransaction is ready for any Transaction. If it is given an Expense, it does not get confused: “okay, that is also a transaction.” But if we tried to do the opposite (substitute a function that can format only expenses where any transaction might be passed) it would be dangerous: it could be given income, and it did not “promise” to handle it.
This example is not here so that you immediately learn the word “contravariance” and say it in an interview with a smart face. It’s here so that you accept the idea: subtyping in generic constructions depends on whether we read values or write them. For functions, “read/write” shows up as “accept an argument / return a result”.
8. Typical mistakes
Mistake #1: “If it’s List, then it’s immutable”.
Beginners often think List is an “immutable list”. In reality, List is a read-only interface: you cannot change it through this reference type, but the collection itself may be mutable somewhere else. Kotlin describes the model exactly this way: there is a read-only interface and there is a mutable interface that extends it with write operations.
Mistake #2: Writing functions that do not change anything but accept MutableList.
This is not just “style”. It is a practical trap: you lose the ability to pass List<Expense> where MutableList<Transaction> is expected, and you get type errors. If you are not going to add/remove elements—accept List, and you automatically get safe type “lifting” for read-only collections.
Mistake #3: Trying to “cheat” the system via casts with as.
Sometimes there is a temptation to do something like val x = expenses as MutableList<Transaction> so it “compiles”. This is exactly the path that leads to runtime problems: you manually disable the compiler’s safety net. If the code is actually unsafe, you are just postponing the crash, making it more unpleasant and less obvious.
Mistake #4: Treating “lifts” and “doesn’t lift” as a random rule.
It’s easy to memorize “List works, MutableList doesn’t” as a magic spell. But it’s much more useful to keep the reason: read-only collections are covariant because you cannot write through them, while mutable ones are not covariant, otherwise you could violate the element type (mix in a different subclass). Kotlin states this motivation directly.
GO TO FULL VERSION