CodeGym /행동 /Kotlin SELF /Type projections: anjeonhan Array<out/in> gwa MutableLi...

Type projections: anjeonhan Array<out/in> gwa MutableList reul wihan projecksyeon

Kotlin SELF
레벨 36, 레슨 2
사용 가능

1. Sogae

modeun geol “keompailleo-ga guman ttokttokhage 굴ji mara” sujeongeuro dan순hwahae beorimyeon, dangyeonhi as reul sseugo geudaero salgo sipseumnida. hajiman Kotlin-eun juistanghagae-do, peurogeuraem-i keompail doe-eotneunde runtaim-eseo eodideun meolli tteoreojin goseoseo teojineun sanghwang-eul uri-reul wihae mag-euryeo hamnida — geurigo geu ttaeneun “naega beon-yeonghi gyeong-gohaetjana” 라neun pyojeong-eul jiggo itjyo.

munje-neun eotteon container-deul-eun bonjiljeogeuro “ilgido hago, sseugido” handaneun jeom-ibnida. geureon container-neun class seoneon-e seo out ttoneun in eul jeongjikage butil su eopseumnida — geureomyeon uimi-ui ban-eul ileobeoril tenikka-yo. gyeongjeonjeogin yeseo-neun Array<T> ibnida. indekseu-ro ilgido hago, indekseu-ro sseugido hal su itjyo. Kotlin-eun i yeseoreul jikeop sseoseo, wae Array ga invarianteu-inji geurigo eotteohge projecksyeon-euro haegyeolhaneunji seolmyeonghamnida.

Type projections neun 타협-ibnida: class Array reul bakkugi neun geon anigo, teukjeong 함수-eseo geu ganeungseong-eul “jallyeo” keompailleo-ga anjeonseong-eul 보장 hal su itge hamnida.

2. Wae Array<T> ga invarianteu-inga

baeyeol-eun “keonteineo-니까 List cheoreom dongjakhaeya haneun geo anya?” 라neun 함정-e ppajigi swip습니다. hajiman Kotlin-eseo List neun “읽기” reul wihan 인터페이스이고, Array neun indekseu jeopgeun-i ganeunghan jinjjaro “indekseu-ro jeopgeunhal su inneun sangja” -yeo서, yeol-eo bogido 하고 mwo든 ji-wodo 다시 넣-eul su it습니다.

dan순hwahaeseo, Array<T> 에는 dae략 ireon yeonsan-i itdago saenggakhal su itsseumnida:

operator fun get(index: Int): T
operator fun set(index: Int, value: T)

geuraeseo Kotlin-eun Array reul (List cheoreom) covariance-ro mandeul su eopseumnida. geureomyeon jal못된 type-eul sseul su inneun gil-i yeollil te니까요. igeu-ga “Array<Int> eseo Array<Any> 로 copy” ga eochiseo keompaildoeji anneun 이유이며, pyeonbeop eopsi-neun seongnipdoeji anneun jeom-ibnida.

jigeum i geol jigeob jeogeuro 느껴 bopsida.

fun copyNaive(from: Array<Any>, to: Array<Any>) {
    for (i in from.indices) {
        to[i] = from[i]
    }
}

fun main() {
    val ints: Array<Int> = arrayOf(1, 2, 3)
    val any: Array<Any> = arrayOf("x", "y", "z")

    // copyNaive(ints, any) // ne compiles: Array<Int> neun Array<Any> ga 아니다
}

igeo-neun joeun il-ibnida. man약 keompailleo-ga heoyonghaetdara면, copyNaive an-eseo iron geosdo teorijeog-euro ganeunhaess-eul geom니다: from[0] = "oops" (jeuk, Int baeyeol-e String eul sseuneun geos). Kotlin-eun i reul mi리 차단haeseo i yuhyeong-ui 실수 class reul ppaepnida.

3. Array reul wihan projecksyeon: out gwa in

Projecksyeon Array<out X>: source baeyeol

함수 매개변수-eseo Array<out Any> reul sseumyeon, keompailleo-e게 ireon uimi-reul jeondalhamnida: “na-neun Any boda deo 나쁘지 않은 element-deul-eul gajigo inneun baeyeol-eul badeul geojiman, geu an-e sseuji anneul geos ira 약속hanta.” 즉, baeyeol-i producer ga doemyeo — 값-eul cungbihaneun source ga doemnida.

철학-eul jal jap-a야 합니다: Array<out Any> neun saeroun baeyeol type-i 아닙니다. gati baeyeol-inde, i chamjo-ro-neun wiheomhan 쓰기 연산-e jeopgeunhal su 없게 (ttoneun type-euro bujeokhaphaege) 만드-neun 것입니다.

Kotlin-eun type projections-eul seolmyeonghal ttae, “modifikasi haji mall아야 하는 baeyeol-eseo boksa하기” 라neun aidee-reul jikeop sseumnida.

Anjeonhan 함수 copyToAny reul sseubnida

from 은 읽기-man 하는 깔끔한 copy reul mandeureobopsida.

fun copyToAny(from: Array<out Any>, to: Array<Any>) {
    for (i in from.indices) {
        to[i] = from[i]
    }
}

fun main() {
    val ints: Array<Int> = arrayOf(1, 2, 3)
    val dest: Array<Any> = Array(3) { "?" }

    copyToAny(ints, dest)

    println(dest.joinToString()) // 1, 2, 3
}

magi cheoreom an boineun magi reul jom bwajuseyo: Array<Int> reul, Array<out Any> reul gidae하는 곳-e 넘겼습니다. igeosi ganeunhan 이유-neun Kotlin-i ije hwaksin하기 때문입니다: from 에 sseuji 않을 geos이고, geureomyeon Int baeyeol-e String eul sseoseo “mangga뜨릴” su 없기 때문입니다. igeo-ga use-site variance / type projection-ui uimi-ibnida.

Array<out X> eseo geumji doeneun geot

keompailleo-ui innae심-eul 시험haego sipdamyeon, ireon geol haeboseyo:

fun breakIt(from: Array<out Any>) {
    // from[0] = "boom" // ne compiles
}

igeon “Kotlin-i gwenhi ggolttongbultonghaneun geot” i 아닙니다. Kotlin-i jeongjikage contract reul 지키는 것입니다: out projecksyeon-eun “ilgi-neun doejiman, sseugi-neun 안 된다” 를 uimi합니다.

Projecksyeon Array<in X>: receiver baeyeol

ije geo울 sanghwang-ibnida. eotteon ttae-neun baeyeol-i source ga 아니라 receiver 로 필요합니다: baeyeol-eul chaewoyaha죠. geureomyeon set yeonsan-i jungyohago, ilgi-neun buchaekjeok-ibnida.

Array<in String> eun ireon deut-ibnida: “String ui supertype eotteon geos-ui baeyeol-inde, geu an-e anjeonhage munjayeol-eul neoh-eul su 있다.”

munjayeol-lo baeyeol chaeugi: fillWithOk

fun fillWithOk(dest: Array<in String>) {
    for (i in dest.indices) {
        dest[i] = "ok"
    }
}

fun main() {
    val anyArray: Array<Any> = Array(3) { 0 }
    fillWithOk(anyArray)

    println(anyArray.joinToString()) // ok, ok, ok
}

wae anjeonhal까요? Array<Any> 는 jina짜로 String eul dam-eul su 있기 때문입니다: munjayeol-eun Any 입니다.

Array<in X> eseo ilgi-ga deo garanghaejineun 이유

yeogi-ga 많은 saram-eul jijeohage haneun (geurigo geu dwi-e-neun iksukhaejyeoseo dareun jumjeom-eul jijeohage doeneun) po인트입니다.

Array<in String> 이면, geu goseoseo String 으로 ilg-eun su 없습니다: silje-ro-neun ige Array<Any> il su 있고, geu an-e munjayeol-man inneun 게 아닐 수도 있기 때문입니다. geuraeseo anjeonhan ilgi type-eun bo통 Any? ga 됩니다.

fun showFirst(dest: Array<in String>) {
    val x: Any? = dest[0]
    println("first = $x") // first = ...
}

fun main() {
    val anyArray: Array<Any> = arrayOf(10, 20, 30)
    showFirst(anyArray) // first = 10
}

다시 한 번: igeon gwenhi ggolttongbultonghaneun 게 아니라 보장입니다. in contract-eun ireon mal 입니다: “na-neun String eul sseul su 있다.” 하지만 geu 안-e 이미 뭐가 들어있는지, geu type-i mwonji-neun amugeotdo 약속하지 않습니다.

4. MutableList reul wihan projecksyeon: out gwa in

baeyeol-e daehaeseo-neun jeongrihaet으니, ije deouk silsaenghwaljeok-in geos-euro 넘어가봅시다: MutableList. igeon uimi-ro “ilgido 하고 sseugido” 하므로, geotdo “geunyang” covariance-ro mandeul su 없습니다. hajiman 함수 매개변수-eseo-neun MutableList reul botae du 가지 mode 중 하나로 sseuneun gyeongu-ga man습니다:

  1. element source-ro (ilgiman 하고 변경하지 않음);
  2. receiver-ro (element reul chu-ga함).

igeu ttae use-site variance ga keun 도움이 됩니다: MutableList<out T> wa MutableList<in T>.

헷갈리지 말아야 할 점: MutableList reul 영구적으로 covariance-ro 만드는 게 아닙니다. “i 함수-eseo-neun 얘를 producer / consumer 로 다뤄라” 라고 말하는 것입니다.

MutableList<out Number>: 숫자를 읽고, 추가하지 않기

예를 들어 MutableList<Int> ga 있지만, 함수는 Number 로 작업하고 싶다고 해봅시다. 프로젝션이 없으면 (mutable collection-ui invarianteu 때문-e) type 호환성에서 막히지만, out projecksyeon-eul sseumyeon — element reul 추가하지 않는 한 문제 없습니다.

fun sumFirstTwo(list: MutableList<out Number>): Double {
    val a = list[0].toDouble()
    val b = list[1].toDouble()
    return a + b
    // list.add(1) // ne compiles: out-projection eun sseugi reul geumji
}

fun main() {
    val ints: MutableList<Int> = mutableListOf(10, 20, 30)

    println(sumFirstTwo(ints)) // 30.0
}

여기서 Kotlin-eun 미묘한 bug reul 막아줍니다: 만약 쓰기가 허용됐다면, Int list-e Double eul 추가할 수 있고, geureomyeon 모 든 게 “흐트러질” 수 있습니다.

MutableList<in Int>: 알맞은 list-e Int 추가하기

이제 반대로: 함수는 Int reul 추가해야 합니다. geureomyeon 더 일반적인 type-ui list, 예: MutableList<Number> reul 넘길 수 있으면 유용합니다.

fun addOne(list: MutableList<in Int>) {
    list.add(1)
}

fun main() {
    val numbers: MutableList<Number> = mutableListOf(10, 2.5)

    addOne(numbers)

    println(numbers) // [10, 2.5, 1]
}

contract-u uimi-neun ireon 것입니다: list-ga Int reul 받을 수 있음이 보장되면, geu element type-eun Int 이거나 supertype (Number, Any) 입니다. igeo-ga 바로 consumer logic 입니다.

5. out / in cheetsheet

프로젝션-eul 처음 쓰기 시작하면, 두뇌-ga 반발합니다: “wae naega wonhaneun-daero geunyang mot-hae?” du뇌가 퇴사하지 않게 하려면 짧은 표를 들고 있는 게 좋습니다.

i dan락 dwi부터는, keompailleo-ga “an dwae” 라고 말할 때마다 언제든 돌아와 볼 수 있습니다.

maegeubyeonsu-eseo projecksyeon aidee pyeonhan geot Kotlin-i uidojeogeuro eoryeopge 하는 geot
Array<out T> / MutableList<out T>
source T ilgi T sseugi
Array<in T> / MutableList<in T>
receiver T sseugi T 로 ilgi (bo통 Any? 로 읽음)

i logic-eun type projections (use-site variance) aidee 와 Kotlin-i type safety reul pag괴할 su inneun yeonsan-eul geumji한다는 jeom-eseo jikeop 따라나옵니다.

6. yeseo: Finance Tracker wa MutableList projecksyeon

“추상적인 gae-wa go양이” 수준-euro namgiji 않도록, projecksyeon-eul siljeon code cheoreom boineun 조각에 심어봅시다.

console app Finance Tracker reul sangsanghaebopsida. 여기에 재무 작업(operations)을 저장합니다. uri-neun ije object collection-eul 저장하고, 함수 reul sseugo, 상속-eul 다룰 줄 아니까, 기본 작업 type-gwa 두 가지 subtype-eul mandeureobopsida.

open class Operation(
    val amount: Double,
    val note: String,
)

class Expense(amount: Double, note: String) : Operation(amount, note)
class Income(amount: Double, note: String) : Operation(amount, note)

작업 출력: producer MutableList<out Operation>

i 함수-eseo-neun 작업-eul 읽어서 출력하기만 하면 됩니다. list-eul 바꾸ji 않아야, 함수-ga gwa-do하게 “gyeonmulyo” 해지지 않습니다.

fun printOperations(ops: MutableList<out Operation>) {
    for (op in ops) {
        println("${op::class.simpleName}: ${op.amount} (${op.note})")
        // Output example: Expense: 12.5 (coffee)
    }
}

fun main() {
    val expenses: MutableList<Expense> = mutableListOf(
        Expense(12.5, "coffee"),
        Expense(40.0, "groceries"),
    )

    printOperations(expenses)
}

wae i ge jungyohal까요? out 없이-nun, MutableList<Expense> reul “operation list” reul gidae하는 곳-e 넘길 수 없었을 것입니다. out 을 sseumyeon, list-ga source 로 사용된다는 점-eul 정직하게 고정합니다.

지출 추가: consumer MutableList<in Expense>

이제 반대 과제입니다: 함수-ga 지출을 추가합니다. geureomyeon MutableList<Expense> 뿐 아니라, 공통 journal MutableList<Operation> 에도 추가할 수 있으면 유용합니다.

fun addExpense(ops: MutableList<in Expense>, amount: Double, note: String) {
    ops.add(Expense(amount, note))
}

fun main() {
    val journal: MutableList<Operation> = mutableListOf(
        Income(1000.0, "salary"),
    )

    addExpense(journal, 12.5, "coffee")

    printOperations(journal)
    // Income: 1000.0 (salary)
    // Expense: 12.5 (coffee)
}

type 관점-eseo-neun ireon sor-i 입니다: MutableList<Operation> 는 Expense reul badeugi-e 완벽한 receiver 입니다, wae냐하면 Expense 는 Operation 이기 때문입니다.

7. projecksyeon-eun object ga 아니라 chamjo-ui API reul jehanhanda

aju jaju saenggineun 혼동: Array<out Any> ga eotteon “teukbyeolhan baeyeol” cheoreom 느껴진다는 점입니다. 하지만 실je-neun baeyeol object-neun geudaero입니다. dal라지는 geon i byeonsu-reul tonghae haedo doeneun il 뿐입니다.

ireon mini diagram-euro sangsanghal su 있습니다:

flowchart LR
    A["Real object: Array⟨Int⟩"]
    B["Reference as Array⟨out Any⟩"]
    C["Reference as Array⟨Int⟩"]

    A --> B
    A --> C

    B -->|"can read (Any)"| R["get(i)"]
    B -.->|"cannot write"| W["set(i, ...)"]

    C -->|"can read (Int)"| R2["get(i)"]
    C -->|"can write (Int)"| W2["set(i, Int)"]

i uimi-eseo projecksyeon-eun aju “engineering” 도구입니다. data model-eul tteutgeochi ji 않아도 됩니다. keompailleo-ga 이해할 su 있는 jehan-eul geoleoseo 말하면 됩니다: “i 함수-eseo-neun na-neun 예의 있게 행동한다.”

8. jibyeonhan silsu

Silsu #1: Array<out …> 또는 MutableList<out …> 에 “deop-seugi” reul 시도하기.
보통 ireon 식입니다: 매개변수를 producer 로 깔끔하게 선언해놓고, 함수 안에서 “geunde jom-man chu-ga할게” 라neun 유혹이 깨어납니다. keompailleo-ga 막습니다. geureo-ya만 합니다: MutableList<Int> 를 MutableList<out Number> 로 넘길 수 있었다면, 2.5 reul 쓰는 순간 논리적 재앙이 될 테니까요.

Silsu #2: Array<in …> 에서 Array<T> 처럼 읽히길 기대하기.
매개변수가 consumer 로 선언되면, Kotlin-eun 의도적으로 읽기를 “bulpyeon” 하게 만듭니다: anjeonhan 읽기 type-eun Any? 같은 모양이 됩니다. igeon 정상입니다. T 로 읽고 T 로 쓰고 싶다면, 그건 더 이상 consumer/producer 시나리오가 아니며 — 아마 이 위치에서는 projecksyeon이 맞지 않을 수 있습니다.

Silsu #3: projecksyeon 대신 as 로 type 불일치를 “치료” 하려고 하기.
“keompail만 되면 돼” 라고 생각하면, 손이 as 로 갑니다. 하지만 generics 에서 type cast 는 컴파일 오류를 “미래의 런타임 surprise” 로 바꾸는 경우가 많습니다. 프로젝션의 장점은 문제를 숨기지 않고, contract를 정직하게 말하게 만든다는 점입니다: “읽기만” 또는 “쓰기만”.

Silsu #4: 프로젝션과 type 선언의 out/in 을 혼동하기.
type 선언에서의 out / in 은 class/interface design 결정입니다 (“i type-eun bonjiljeogeuro producer”). 함수 매개변수에서의 프로젝션은 국소적 결정입니다 (“i 함수-eseo-neun i container-reul producer/consumer 로 사용한다”). 실무에서는 서로 다른 레벨이며, 스스로에게 이렇게 말해두면 좋습니다: “지금 나는 type-eul 설계하는 중인가, 아니면 안전한 함수 signature 만 만드는 중인가?”

Silsu #5: 읽기도 하고 쓰기도 하는 만능 함수를 만들려고 하기.
가끔 “복사도 하고, jom-man 손도 보고” 같은 함수를 만들고 싶고, 매개변수는 가능한 한 넓게 받고 싶습니다. 하지만 invarianteu가 말하는 건 이것입니다: 읽고 쓰려면 정확한 type 을 받아라 (Array<T>, MutableList<T>). 더 넓게 받고 싶다면 — 어딘가를 희생해야 합니다 (보통 쓰기 가능성 또는 읽기의 정확한 type).

1
과제
Kotlin SELF, 레벨 36, 레슨 2
잠금
상자 옮기기
상자 옮기기
1
과제
Kotlin SELF, 레벨 36, 레슨 2
잠금
라벨 채우기
라벨 채우기
1
과제
Kotlin SELF, 레벨 36, 레슨 2
잠금
센서 측정값 합계
센서 측정값 합계
1
과제
Kotlin SELF, 레벨 36, 레슨 2
잠금
숫자 추가
숫자 추가
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION