1. Sogae
Uri-ga “subtype relationship”eul malhal ttae botong sangsok(inheritance)eul tteoollirimnida: han type-i dareun type-eul 확장합니다. Geurigo ilbanjeogin (non-generic) sanghwang-eseoneun modeun ge pretty linearly dongjakhamnida: Expensega Transactioneul sangsokhamyeon, Transaction type variable-eun Expensee daehan reference-reul gajil su itsseumnida. Ige polymorphism-ui gibon-imnida: “base class jari-e derived class-reul neoeodo 된다”.
Ireul uri gaejeong-ui jaemu gwanli yongdo-ui 가상의 앱 (ireum-eul BudgetTracker라고 해봅시다)eseo jageun code jomgag-euro hwaginhaebopsida. Yeogiseo transaction-eun base type, expense-neun transaction-ui guchejeog jongryu-imnida:
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
}
Ige 논리적으로 boyeojyo: expense-neun transaction-ini “transaction” variable-i georeul gary킬 su itsseumnida. Geurigo yeogiseo swipge daeum “直感적” step-eul 밟게 되는데… angle bracket-ga deureoganeun sungan, ge intuision-i hangsang matneun geon aniraseo munjega saenggimnida.
2. Wae Box<Expense>neun Box<Transaction>i anin-ga
Type Treul gajigo jeoncheong container Box<T>euro gamssaneun sungan, saeroun entity-ga saenggimnida: Tga anira “Tga deureo inneun box”imnida. Geurigo yeogiseo Kotlin-eun default로 gajang 조심스러운 seontaeg-eul hamnida: generic type-eun default로 invariant— jeuk, “inheritance-e ttareun automatic substitution-eul bojanghaji anneunda”neun tteut-imnida.
Gajang dan순한 “box”reul mandeureobopsida:
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
}
Saram 입장에서는 ireon mal-i 나올 su itsseumnida: “Expensega Transactionui subclass-inde, expense box-do transaction box-ya.” Hajiman compiler-neun donguihaji 않습니다. Geurigo geureon geon “kkaṭṭaegi”ga anirago, 미리 방지하는 것입니다: “transaction box”라고 믿고 있는 reference-reul tonghae ge 안에 expense-ga 아닌 dareun ge (yemun: income)reul neoh-eobeorimyeon, an-e Expensega 들어 있다고 가정한 type safety-ga 깨지게 됩니다.
Yeogiseo gwiyeok-eul manhi cchida: element subtype relationship-eun container subtype relationship-euro geunyang 옮겨지지 않는다. Daeum-e Liste daehaeseoneun Kotlin-i wae “좋은 예외”reul haneunji, geurigo MutableListe daehaeseoneun wae an haneunji bomo겠습니다.
3. Wae List<Expense>reul List<Transaction>cheoreom sayonghal su inneun-ga
Jigeum Kotlin-eseo manhi heunhi 헷갈리는 jungyohan point-ga 나옵니다: Listneun “geunyang list”ga anira read-only interfaceimnida. 크기 조회, index로 element 가져오기, iteration 등 “읽기” operation-man 제공하고, “추가/삭제”는 제공하지 않습니다. Kotlin standard library-neun collection-eul read-only와 mutable interface로 분리합니다: 읽기 전용 interface와 읽기+쓰기 interface가 별도로 있습니다.
Geu 핵심은 이것입니다: Kotlin-eseo read-only collection-eun covariant—즉, Rectanglega Shapereul sangsokhal ttae List<Rectangle>reul List<Shape>reul yeongyeokhan 곳에 neoeo도 된다는 뜻입니다. Saram mal-ro: “읽기만 하는 list라면, 더 구체적인 element list를 더 일반적인 element list로 다뤄도 안전하다.”
Uri transaction yemu-euro 옮겨 봅시다:
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
}
Wae anjeonhal까요? Variable transactionsreul tonghae 절대 transactions.add(...) 같은 일을 할 수 없기 때문입니다—List에는 그런 operation이 없습니다. Geureomyeon 원본 expenses list 안에 다른 transaction을 “섞어 넣는” 일이 발생할 수 없습니다. 이미 들어 있는 것을 읽기만 합니다.
Ginyeom-eul dahgi wihae contract-reul bigyohaebopsida:
| Type | Can read elements | Can add/remove |
|---|---|---|
|
yes | no |
|
yes | yes |
Geureoneun i read-only interface ttaemun-e Listreul sangwi type-euro “올리는” geot-eul Kotlin-i 허용합니다.
Jungyo: read-only-ga “영원히 불변(immutable)”이라는 뜻은 아닙니다. Listneun data-ga eodideun dareun got-eseo jeoldae byeonhaji anneunda-go 약속하는 게 아니라, i reference type-eul tonghae-seoneun collection-eul mutate할 수 없다고 약속합니다. Kotlin-eun read-only vs mutable interface model-eul 정확히 이렇게 설명합니다.
4. Wae MutableList<Expense>reul MutableList<Transaction>cheoreom sayonghal su eomneun-ga
Jigeum-i ya말로 “아픈” part입니다: wae compiler-ga geot-i so logicalha다고 느껴지는 것을 geujeoldanghaneunji. Haegdoroun iyu han 가지에 달려 있습니다: MutableListneun 쓰기(write)를 허용한다.
Kotlin-i man약 아래 줄을 허용한다고 가jeonghaebopsida:
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 Income, breaking the type!
}
Variable txsga “transaction list”라면, contract상 Income(...) add하는 것은 완전히 합법입니다. Hajiman 실제로는 그 객체가 expenses(expense list)와 동일한 object라면, 방금 우리는 expense list 안에 income을 조용히 섞어 넣은 것이 됩니다. Type safety 위반이죠: MutableList<Expense>ga 더 이상 “진짜 Expense list”가 아니게 됩니다.
Geuraeseo Kotlin-eun 엄격한 규칙을 둡니다: mutable collection은 covariant가 아니다. 그렇지 않으면 runtime 문제와 type contract 붕괴로 이어집니다.
Practice-eseo-neun 대략 아래와 같은 error를 보게 됩니다 (문구는 조금 달라질 수 있지만 요지는 같습니다):
Type mismatch: Required `MutableList<Transaction>`, found `MutableList<Expense>`
Ige 바로 “compiler-ga 일을 방해한다”가 아니라, 미래에 데이터가 깨질 상황을 미리 막아주는 전형적인 케이스입니다.
5. Mental model: “output(제공)” vs “input(수용)”
Baneun-eul juwoeobsida. Geunyang jumuneun eoupsida. Sillohage ihaehagi wihan il상 analogi-ga yuyong합니다. 창구가 있는 창고를 상상해 보세요. Han 경우엔 받기만 가능합니다(“지급/출고”), dareun 경우엔 받아들이기만 가능합니다(“입고/수납”), 세 번째는 둘 다 됩니다(그럼 누군가 반드시 “다른 물건”을 가져오면서 재미(?)가 시작됩니다).
Read-only Listneun “출고”에 가깝습니다: element를 꺼내어 읽을 수만 있습니다. Geuraeseo “expense 창고”를 “transaction 창고”로 봐도 됩니다. 모든 expense는 transaction이므로, transaction으로 읽는 것은 안전합니다.
MutableListneun “출고+입고가 동시에”입니다: element를 꺼낼 수도 있고 새 것을 넣을 수도 있습니다. Yeogiseo type substitution이 위험해집니다: “transaction 입고”를 받았다고 생각하고 income을 넣을 수 있는데, 실제로는 “expense 입고”였다면 혼란이 발생합니다.
Mworisoge geol리ge han neun jageun diagram:
flowchart LR
A["List⟨Expense⟩
(read-only)"] --> B["List⟨Transaction⟩
(read-only)"]
C["MutableList⟨Expense⟩
(read+write)"] -.-x D["MutableList⟨Transaction⟩ (read+write)"]
Solid arrow-neun “안전하게 대입 가능”, dotted line with X-neun “위험하므로 금지”를 의미합니다.
6. Practice in BudgetTracker: “올바른” list 받기
Real code-eseo MutableList<Expense>로 인한 고통은 보통 추상 예제가 아니라, 유용한 함수를 만들면서 “그냥 list 하나 받으면 되지”라고 생각하는 순간에 나타납니다. 예: 합계 계산, 콘솔 출력, 최대값 찾기, 정렬, 그룹화.
Yeogiseo 가장 중요한 실전 조언은 Kotlin model에서 직결됩니다: 함수가 반드시 collection을 바꿔야 하는 게 아니라면, MutableList가 아니라 List를 받으세요. Geureomyeon API가 더 유연해지고, read-only collection에서의 type “promotion”도 자동으로 얻습니다.
Uri app-eseo base type-gwa 두 가지 operation(출력, 합계 계산)을 만들어 봅시다. 둘 다 list를 mutate하지 않습니다.
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
}
Yeogi “magic without magic”reul bwas죠: printTransactionsneun List<Transaction>reul 기대하지만, 우리는 List<Expense>reul 전달했고 문제없이 동작합니다—List가 read-only이고 covariant이기 때문입니다.
Ijen list를 mutate하고 싶어하는 function 예시입니다—예를 들어 transaction을 하나 추가한다든지. Yeogiseoneun “아무거나 그냥 받기”가 안 됩니다:
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
}
Geurigo i-sanghan (하지만 중요한) 관찰: eotteon got-eseo MutableList<Expense>reul 가지고 있다면, georeul addTestTransactione 넘길 수 없습니다. (Wae냐하면 잠재적으로 위험하기 때문—이미 위에서 다뤘습니다.)
Tteoneun “saengjon tactic” 하나 (오늘은 type system-ui teukbyeolhan 도구들을 아직 다루지 않는다고 할 때)는, “잠깐 mutate해야” 한다면 복사본을 만드는 것입니다:
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 copies. Yes, it costs memory and time. But it is honest: we do not break the original expensesOnly list, and we work with a separate mutable copy. This is a perfectly reasonable “bridge” until you have more precise type contracts.
How to read compiler messages about List and MutableList
Compiler messages in these places are usually short but annoying. The main beginner mistake is to treat them as a “mysterious prohibition” rather than as a hint about what could go wrong.
If you see that List<Expense> does not fit where List<Transaction> is expected, then most likely somewhere you are actually using a mutable type, not List (or expecting one). In Kotlin, read-only collections are covariant, but mutable ones are not. So the first thing to do is check the function signature: do you really need MutableList there?
If the message says MutableList<Transaction> is required but you have MutableList<Expense>, it almost always means: “I see you want to write into the collection, and that would be unsafe under this substitution.” Then you have options: redesign so the function accepts List and does not mutate; store data differently; or explicitly copy into a more general type, as shown above.
Also remember: Kotlin clearly separates read-only and mutable collection interfaces. Sometimes it is enough to change MutableList to List in a parameter, and half of the “weird” problems disappear.
7. Function analogy: why (Transaction) -> String fits where (Expense) -> String is expected
There is another interesting piece that helps your brain get used to the idea that “substitution does not always work the way it seems.” This is about function types.
In Kotlin, a function is also a value, and it has a type like (A) -> B: it takes A and returns B. The logic is straightforward: if a function can accept any transaction, then it can definitely accept an expense (because an expense is a special case of a transaction).
From the type point of view, it looks “reversed” compared to lists: for the input parameter, the function behaves as if substitution works in the opposite 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 receives an Expense, it is fine: “okay, that is also a transaction.” But if we tried to do the opposite (use a function that can format only expenses in a place where any transaction might be passed), that would be unsafe: it could receive an income, which it never promised to handle.
This example is not here so you can memorize the word “contravariance” and drop it in an interview. It is here so you accept the idea: subtyping for generic constructs depends on whether we read values or write values. For functions, “read/write” shows up as “accept an argument / return a result.”
8. Common mistakes
Mistake No. 1: “If it is List, then it is immutable.”
Beginners often think List means an “immutable list.” In reality, List is a read-only interface: you cannot change it through this reference type, but the underlying collection may still be mutable somewhere else. Kotlin describes the model exactly like this: there is a read-only interface and there is a mutable interface that extends it with write operations.
Mistake No. 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 “promotion” for read-only collections.
Mistake No. 3: Trying to “cheat” the system with casts using as.
Sometimes there is a temptation to do something like val x = expenses as MutableList<Transaction> just to “make it compile.” This is exactly the path that leads to runtime problems: you are manually turning off the compiler’s safety net. If the code is actually unsafe, you are only postponing the crash, making it more painful and less obvious.
Mistake No. 4: Treating “it promotes” vs “it does not promote” as an arbitrary rule.
It is easy to memorize “List works, MutableList does not” like a magic spell. But it is much more useful to keep the reason: read-only collections are covariant because you cannot write through them, and mutable collections are not covariant because otherwise you could violate the element type contract (mix in a different subtype). Kotlin states this motivation explicitly.
GO TO FULL VERSION