1. Wae generics-ga piryohago, keollekshyeon tipeul eotteohge ilgeulkka
Chogeumssik sijakhaneun jungiramyun, genericsreul swipge “salmeul banghaehaneun isanghan samgak goeryeokgwolho”ro neukkil su itsseumnida. Hajiman hyeonsireseo geugeon bogoep-eul bangjihaneun boheomjangchiimnida. Kotlin-eun jeongmal tipeul chujeonghal jul algo, geureona tipeu chujeong-eun telepathy-ga anibnida: keompailleoneun dangsini jumeon geoseul baetang-euro samseumnida. Deiteoreul keollekshyeon-e damneunda-myeon, keompailleoga an-e mueos-i deureoitneunji jeonghwakhi alagaya hamyeo, geureoji anh-eumyeon uiyeong-euro gabsdeuli seokyeo deureoganeun geoseul bangjihal su eopseumnida.
“Seoltang” irago jeok힌 jumyeong-i itneun jubang yonggireul sangsanghaeboseyo. Generics-ga baro geu jumyeong-imnida. Mueosideun geu an-e neoeul su itjiman, jumyeong-i “Seoltang” imyeon jeo-geun-do chareul masils ttae geu an-eseo “bolteu du gae”reul deoreonaeryeogo haji anneungeoya. Banhadaero yonggireul jumyeonghaji anh-eumyeon, eoneu nal juk-eseo USB reul chajge doel su itsseumnida. “Eotteon gyeongwirodeun geuro geu an-e deureogasseo” gateun ireul.
Kotlin-eseo geu jumyeong-eun ireon hyeongtaero boyeom니다: List<String>, MutableList<Int>, Map<String, Int>. Geugeon dan순 han jangshik-i anira — keompailleoga dae신 geomjeonghae juneun contract imnida. Kotlin-eseo generics-ui haeksim gaenyeom-eun “ilbanhwa doen tipeu pa라미teo” (type parameters) 로 seolmyeongdoemnida.
Ije momeun “sori-reul kkeo beor릴” su inneun sungan-i ol su isseunikka, 미리 약속haejyo: genericsreul “gimun”euro ilneun 게 아니라 hangug-eo munjang-euro ilgseumnida. List<T> reul bomyeon “T tipeu element-ui list” 라고 malhago, Map<K, V> reul bomyeon “K tipeu key-e서 V tipeu value 로 ganeun map” 라고 malhabnida. Yeoreot beon banbokhamyeon, println eul ilgneun geot cheoreom jayeonseureoun seupgwan-i doemnida.
Kotlin keollekshyeon-eun inteopeiseuwa hierachy-ga 있지만, oneul-un geugeotboda tipeu contract ga deo jungyohamnida: conteineoneun jeongsinhan jonglyu-ui element man-eul gajigo itda. Yaksok-eun da eum:
- List<T> neun elementreul 순서대로 boyu-hago indexro jeobgeunhal su itsseumnida.
- Set<T> neun jungbok doeneun element eopsi yuilhan elementreul boyu-hamnida.
- Map<K, V> neun “key → value” jjag-eul boyu-hamnida.
Jageun pyo: “eotteohge ilg-eulkka”
| Tipeu pyohyeon | Eotteohge ilg-eulkka | Gabs 예시 |
|---|---|---|
|
string list | |
|
byeongyeong ganeun int list | |
|
yuilhan string set | |
|
“string → int” map | |
Geurigoh, majimak-euro i modeun geos-eun “siljero mueos-i deureoitneunji” ga anira, “mueos-eul neotgo kkeonael su inneunji”e daehan iyagieyo.
Tipeu chujeong: bin keollekshyeon-eun wae eoryeopgo, an bin keollekshyeon-eun wae swip-eulkka
Chobojaga gajang jarju mannaneun sanghwang: “bin listreul mandeureossneunde Kotlin-i kkeul-eul geonneunda. 똑똑하잖아?” Kotlin-eun 똑똑hajiman jeomsulga-neun 아닙니다. mutableListOf() reul element eopsi sseumyeon, keompailleoneun eotteon gabsdo mot bwaseo T ga mueos-inji al su eopseumnida. Geureoke doeneun 게 당연하죠: “mueos-ui list” 인지 — string, number, triple record, 고양이.
Element-ga inneun keollekshyeon-eun swipseumnida: Kotlin-i elementreul bogo geu gabsdeulro tipeul chujeonghamnida. Igeon type inference-ui pyojun jeok dongjag-imnida: konteksuteu-eseo hanahanae gyesan dwaemyeon tipeu argumentreul giesullaji anado doemnida.
Ye: element-ga isseose tipe-i jayeonseureopge chujeong됨
fun main() {
val names = listOf("Ann", "Bob") // List<String>
val nums = mutableListOf(1, 2, 3) // MutableList<Int>
println(names) // [Ann, Bob]
println(nums) // [1, 2, 3]
}
Ye: bin keollekshyeon — tipeul hinto jwoya ham
fun main() {
val tags = mutableSetOf<String>()
tags.add("kotlin")
println(tags) // [kotlin]
}
Wae yeogin gwaenchankayo? <String> reul malhaetgi ttaemune, keompailleoga an심hago tipeul 확정haesseumnida.
Tipeul hinto juneun du 가지 bangbeop
Gga끔-eun o-reunjjok-e tipeul sseuneun 게 pyeonhals 때가 itsseumnida:
fun main() {
val ids = mutableListOf<Int>()
ids.add(10)
println(ids) // [10]
}
Dareun ttae-neun oenjjok-e, teukhi tipe-i gildeomyeon:
fun main() {
val ids: MutableList<Int> = mutableListOf()
ids.add(10)
println(ids) // [10]
}
Du bangbeop modu dongilhage dongjaghani, gadokseongi deo joheun jjok-eul seontaekhamyeon doemnida.
2. Map-e daehan gajang jungyohan sasil: map[key] neun V? reul banhwanhanda
List neun daebubun 직관jeog입니다: index-ga itgeona eopsgeona, eopseumyeon error-ga na서 geum방 “mwo-reul haesseo?”reul al게 됩니다. Hajiman Map eun dareuge dongjakhaneunde, key-ga eopsneun 게 jinjja ro jaju inniun-ilgi ttaemun입니다. Geuraeseo Kotlin-eun key-ro 읽gi-reul 할 때 V ga 아니라 V? reul jumnida. Geureoji aneumyeon “eopsneun key” ttaemune bulpilyohan crashreul neomu jarju mannage doel geoyeyo.
Ye: read-eun Int? reul junda
fun main() {
val prices: Map<String, Int> = mapOf("tea" to 90)
val teaPrice: Int? = prices["tea"]
val milkPrice: Int? = prices["milk"]
println(teaPrice) // 90
println(milkPrice) // null
}
Elvis ?: — 예비 플랜
fun main() {
val prices = mapOf("tea" to 90)
val milkPrice = prices["milk"] ?: 0
println(milkPrice) // 0
}
Igeon “pyeonseop” i anieyo. Geunyang jeongsik-jeogigo jeongjikhan contract-imnida: “gabs-i iss-eul 수도, null il 수도 있다.”
Eonje containsKey ga ?: boda deo mateul까
Gga끔-eun “key-ga eopsda” wa “value-ga 0 ida” reul gu분haego sip-eul 때가 있습니다. Geureom key jonjae 여부를 먼jeo geomsa-haneun 게 hap리적입니다:
fun main() {
val stock = mapOf("apple" to 0)
val key = "banana"
if (stock.containsKey(key)) {
println("Key-ga issgo, value = ${stock[key]}") // 실행 안 됨
} else {
println("Key-ga eopseum") // Key-ga eopseum
}
}
3. Jungcheop genericsreul apeuro teol-eo beor리지 ango: gadokseong sal리gi
Yeogi-seo manhi-deul ireohge tipeul sseuda-ga “peurojekteu-e demons-eul jeonghwa-haejul sajeb-eul bulleo야 hana?” sip-eun geosdeul-eul man듭니다: MutableMap<String, MutableList<Triple<String, String, Int>>>. Beopjeok-euro neung-hajiman gadokseong-i manggajimnida. Oneul-un du 가지 techneul ikeoseumnida: cheot째, junggan val reul ju저하지 mal 것; dul째, joh-eun byeonsu ileum-euro tipeul kode-eseo “nune tteuge” hal 것.
즉, uri-ui mokpyoneun “tipeul sseuneun 것” i 아니라 “salamdeuri museowohaji anh게 tipeul sseuneun 것”입니다.
Gadokseong-eun 나쁘지만 compile-doem
fun main() {
val data: MutableMap<String, MutableList<Triple<String, String, Int>>> = mutableMapOf()
println(data) // {}
}
Yeo-geon yugi hwahak gongshik cheoreom boyeoyo. Mat-eul su-neun 있지만, “masigo sipji” aneun neukkim.
Deo joheun bangbeop: uimireul dareun deung-ro 나누gi
fun main() {
val byCategory: MutableMap<String, MutableList<Triple<String, String, Int>>> = mutableMapOf()
val foodRecords: MutableList<Triple<String, String, Int>> = mutableListOf()
foodRecords.add(Triple("food", "coffee", 300))
byCategory["food"] = foodRecords
println(byCategory) // {food=[(food, coffee, 300)]}
}
Ajik “yeppeun keollekshyeon operation”eul baeugi jeon-iranikka, gibon dongjagman sseumnida: saengseong, chuga, key-ro dae입.
4. Silseup peurojekteureul wihan choeso deiteo gujo
Ije peurojekt yong deiteo “skelet”eul mandeureo boseyo. I skelet-eun imi yuyohajiman class-na bokjaphan architecture-eul yoguhaji anhseumnida. Keonsol mini jichul teurekeoreul 만든다고 sangsanghaeboseyo. Gak record-eun category, seolmyeong, geurigoh geum-aeg-i itsseumnida. Igeon Triple<String, String, Int>e maemdol-gi joheoyo: se pild, dan순han contract. Triple eun daehyeong peurojekteu-eseo gadokseongi joheun hyeong태-neun 아니지만, chogireun “pild 순서”reul 엄격하게 지킨다는 jeon제 ha-e dae체 도구로 괜찮습니다.
Dong시에, manhi record-eul dam-eul conteiner-ga piryohamnida. Geu ttaemun-e MutableList<Record> ga majseumnida. 여기에 Record eun uri Triple<...> 입니다.
Step 1: record 형식-e daehan 합의
fun main() {
val record = Triple("food", "coffee", 300)
println(record.first) // food
println(record.second) // coffee
println(record.third) // 300
}
Mat아요, first/second/third neun gadokseong-ui kkum-eun 아니지만, 지금은 괜찮습니다.
Step 2: list-e record 보관하기
fun main() {
val records: MutableList<Triple<String, String, Int>> = mutableListOf()
records.add(Triple("food", "coffee", 300))
records.add(Triple("transport", "taxi", 1200))
println(records.size) // 2
}
MutableList neun Kotlin-ui pyojun byeongyeong ga-neung list로, add/remove deung-ui byeongyeong operation-eul jeong상적으로 jiwonhaemnida.
Step 3: class eopsi identifier chuga하기
Mae우 jarju piryohan 기능: recordreul id ro chamjo할 수 있어야 합니다. Class가 있다면 id fieldreul mandeureosseul geoyeyo. Hajiman 아직 OOP 없이 가는 중이니, Map<Int, Record> reul 사용합니다.
Yeogiseo Map contractreul gieokhaeya 합니다: key-neun yuilhago, key-ro jeobgeunhamyeon null i dol-awa-ol su itsseumnida.
fun main() {
val byId: MutableMap<Int, Triple<String, String, Int>> = mutableMapOf()
byId[1] = Triple("food", "coffee", 300)
byId[2] = Triple("transport", "taxi", 1200)
val found = byId[2]
println(found) // (transport, taxi, 1200)
}
Step 4: memori-sang peurojekt minimum state
Ije modeun geoseul han kkyeo-e moaseo 봅시다: record list (chugahan 순서를 yujihagi wiham) 와 id map (ppal리 chatgi wiham) 입니다. Mat아요, dubun-ui storagereul gajigo, dong기화는 수동 disciprine입니다. Hajiman 우린 architecture bok잡seong 없이 minimum 버전을 만드는 중입니다.
fun main() {
var nextId = 1
val records: MutableList<Pair<Int, Triple<String, String, Int>>> = mutableListOf()
val byId: MutableMap<Int, Triple<String, String, Int>> = mutableMapOf()
val id = nextId++
val record = Triple("food", "coffee", 300)
records.add(id to record)
byId[id] = record
println(records) // [(1, (food, coffee, 300))]
}
Yeogiseo-neun to (infix function) reul sseoseo Pair reul mandeul-e, record ga “id to record” cheoreom boyige 합니다. Igeon “id-ga record-e hae당한다” cheoreom 거의 자연-eopeun munjangcheoreom ilg힙니다.
API design-eseo-ui generics: List<T> vs MutableList<T>
I ttae naseoneun se밀hajiman mae우 sil용jeog-in 원칙이 생깁니다: 함수가 keollekshyeon-eul byeongyeonghae야 할 이유ga 없다면, mutable version boda read‑only 타입(List, Map, Set) eul 받는 게 낫습니다. Igeon kode-reul deo anjeonhage mandeureo 줍니다: “yeogin geunyang 읽gi만 한다” reul 타입으로 bakkul su itsseunikka요. Kotlin-eun read‑only 와 mutable keollekshyeon-eul inteopeiseu 로 분리하는 standard ideareul gajigo 있습니다.
Jageun 예로 bogetseumnida: recordreul chulryeokhaneun 함수가 있다고 합시다. Geu 함수는 add/remove ga piryohaji 않고, geunyang 순회하며 출력만 하면 됩니다.
fun printRecords(records: List<Pair<Int, Triple<String, String, Int>>>) {
for ((id, record) in records) {
val category = record.first
val title = record.second
val amount = record.third
println("#$id [$category] $title = $amount")
}
}
fun main() {
val records = mutableListOf<Pair<Int, Triple<String, String, Int>>>()
records.add(1 to Triple("food", "coffee", 300))
printRecords(records)
// #1 [food] coffee = 300
}
Jujuhaeboseyo: uri-neun recordreul chuga-haeya 하므로 MutableList e 저장하지만, 함수에 neoleul ttae-neun List 로 jeondal합니다. Hamsu-neun “ilgeuneun saram” i니까요.
Key jeonggyuhwa: Mapeul sal리는 seupgwan
Map eun user input-eseo on “deoreoun string”eul key-ro sseugi sijakhamyeon, 갑자기 munje-ga doeneun areum다운 도구입니다. Userga " Food ", daeum-en "food", daeum-en "FOOD" cheoreom sseumyeon, peuro그램은 se gaji reul dareun category로 cheorih게 됩니다. Peuro그램-i jal못 haenneun 게 아니라, dangsin-i se gaji dareun string을 준 것입니다.
Geuraeseo dan순han seupgwan-eul 고정합니다: string을 key로 sseugi jeon-e jeonggyuhwa 한다. Yeogi-seon trim() gwa lowercase() 면 충bunya 합니다.
fun normalizeKey(raw: String): String {
return raw.trim().lowercase()
}
fun main() {
val categories: MutableSet<String> = mutableSetOf()
categories.add(normalizeKey(" Food "))
categories.add(normalizeKey("food"))
categories.add(normalizeKey("FOOD"))
println(categories) // [food]
println(categories.size) // 1
}
Igeon Set (yuilseong) gwa string jeonggyuhwa-ga hamkke 예측 가능한 동작을 만들어 주는 좋은 예입니다.
5. Jeonhyeongjeog silsu
Silsu #1: “Kotlin-i 똑똑하니까 알아서 하겠지” — tipeu eopsi bin keollekshyeon saengseong.
Bin keollekshyeon-eun elementga eopseunikka, keompailleoga T reul chujeonghal jaeryoga eopseumnida. Geu gyeolgwa tipeu chujeong errorreul man납니다. Haegyeol-eun dan순합니다: tipeul myeong시하세요. factory에 <T> reul 붙이거나 (mutableListOf<String>()), oen쪽-e tipeul sseoseo 해결합니다 (val xs: MutableList<String> = mutableListOf()).
Silsu #2: Map<K, V> 와 map[key] ui gyeolgwareul hon동.
Map 안의 value tipe-i nullable i 아니어도 (V), key로 읽으면 V? reul 돌려줍니다. Key-ga 없을 수 있기 때문입니다. Igeoreul 잊고 “jeoldae null i 아니다” cheoreom sseury면, 곧바로 compile error (joheun kyeongu) 를 만나거나 !! 를 남발하는 (najjeun kyeongu) 길로 갑니다. Jeongsanghan jeollyak-eun ?: 또는 key jonjae 여부 확인입니다.
Silsu #3: jungcheop generic tipeul “gadokseong” eul saenggakhaji 않고 gyesok 키우는 것.
MutableMap<String, MutableList<Triple<String, String, Int>>> gateun tipe-un eul-eumyeon mat-eul su 있지만, ilgiga himdeumnida. Teukhi 초보자(geurigoh ilju일 뒤-ui 자기)에게요. Junggan byeonsu-reul ingan-jeogin ileum-euro 나누고, jageun step-euro jinhaenghamyeon sal-a-namnida: meonjeo list, daeum map, daeum geu sai-ui yeongyeol.
Silsu #4: “eonjen-ga byeongyeonghal지도 모르니까”라며 모든 함수에 MutableList 와 MutableMap 을 넘기는 것.
Igeon chaegim gyeonggye-reul muneotteur립니다: eoneu 함수든 “u연히 deiteo-ui ban-eul jiwo beor릴 권한”을 가지게 됩니다. Ham수가 읽gi man haeya 한다면, read‑only 타입의 List/Map/Set 을 받으세요. Kotlin-eun 예측 가능한 코드를 쓰도록 read‑only 와 mutable inteopeiseureul deliberately 분리해 두었습니다.
Silsu #5: user input-eul jeonggyuhwa 없이 geudaero key-ro sseuneun 것.
trim().lowercase() reul 하지 않으면, "food", " Food ", "FOOD" ga 서로 다른 key-ga 됩니다. Peuro그램-i “mangga진 것” cheoreom boyjiman, silje론 string을 neomu geunyang geudaero 받았기 때문입니다. Jeonggyuhwa-reul seupgwan-euro mandeureo duseyo — geureom Map eun suryung한 도구가 doego, “sunggweul mandeuneun gigye”ga ani게 됩니다.
GO TO FULL VERSION