CodeGym /행동 /Kotlin SELF /Tyip geomsa mit tyip byeonhwan: is, smart cast, as, as...

Tyip geomsa mit tyip byeonhwan: is, smart cast, as, as?

Kotlin SELF
레벨 34, 레슨 3
사용 가능

1. Sogae

Peurogeuraeming-eul cheoeum sijakhals ttaeneun ireoke saenggakhagi swipjyo: “naega val x: String eul sseosseumyeon, geugeon munjayeol-i go kkeut.” Daebubun-eun jeongmal geureohgo, Kotlin-eun yeoreobuni pyeonhage sal su itdorok haejumnida. Hajiman hamseu-reul sseugi sijakhago, deo ilbanjeogin tyip (yep: Any tto-neun base keullaeseu) eul badeun hamseu-reul mandeulgi sijakhamyeon, hyeonsil-eul mannage doemnida: i byeonsu-eseoneun dareun hyeongtae-ui data-ga deureool su itseumnida. Geureomyeon “jigeum geu an-e mu-eot-i deureoitji? geurigo i object-e daehae method-reul bulaedo doelkka?”raneun munjega saenggimnida.

Uri-ga sangsanghaneun keonsol gajyeongbu (gangjwa-ui gasa app)reul tteoollyeoboseyo: geu an-eneun “naebu” model Expensega itsgo, sayongja ibryeok-eun munjayeol-imnida. Eotteon ttaeneun bojo hamseu-reul sseo서 “mueodeunji”(munjayeol, suja, null) reul bad-a geu geos-eul geumaek-euro bakkwo boryeogo hamnida. Ttoneun yeonsan gyeolgwa-reul cheorihaneun handler-reul sseuneunde, banhwan tyip-eun ilban tyip-igo naebu-eneun yeoreo gyeolgwa hyeongtae-ga jonjaehaneun gyeongu-do itseumnida. Ireohan gos-eseo Kotlin-eun uri-ege “soljikhaejeora”go haeyo: meonjeo tyip-eul geomsa hage, geu daeum sayonghago.

Any wa Any?: gajang ilbanjeogin tyip

Kotlin-i eomgyeokhan seonsaengnim-ira면 Anyneun “eotteon geot-ina gajigo wa. hajiman na jung-e mu-eot-eul gajigo wasneunji mul-eul geoya”raneun hwangyeong-gat-eun mal-ipnida. Any tyip-eun “eotteon non-null object”reul uimihamnida. I geos-i jungyohamnida: nulleun Any tyip-ui gachi-ga anipnida. waenyahamnyeon Anyneun non-null-igi ttaemunimnida. “nulldo podamhaeseo eotteon geot-ina”reul wonhamyeon Any?reul sseoya hamnida.

Anyneun jeongmal로 jeonghwakhan tyip-eul sajeon-e alm su eopseul ttae yuyonghamnida: yep-eul deulmyeon “dareun jonglyu” gachi-ga 섞인 collection, yobeomhan parser, logging hamseu, oe부 data 위-e adaptor. Hajiman Anyeun daega-ga itsseumnida: byeonsu-ga Any tyip-in 동안, String ui method-reul baro buleona, .lengthreul bara bol su eopseumnida. Meonjeo “jeongmal munjayeol이다”(tto-neun dareun 구체 tyip)raneun geos-eul keompailleo-ege jeungmyeonghaeya hamnida.

Jal gieokhagi wihan jageun pyo ib니다:

Tyip Uimi null jeojang ganeung?
Any
eotteon object an doe
Any?
eotteon object tto-neun null doe

2. Tyip geomsa: is wa !is

is yeonsanja-neun “tyip tamjigi” imnida. silhaeng sigan(runtime) e gachi-ga jeonghaejin tyip-e soghae haneunji geomsa hamnida. maj-eumyeon jogeon-i cham, 아니면 geojit-imnida. “I tyip-i 아니다”ro ilgego sip-eumyeon !isdo itseumnida.

Deo 좋은 jeom: isneun 보통 smart cast(umjeonhan byeonhwan)reul bal동합니다. 즉 if mun-ui haedang branch 안에서는 byeonsu-reul deo 구체-jeogin tyip-cheoreom — myeongsi-jeogin as eop-si — jeobge hal su itsge haejumnida. i geot-eun da-eum jeol-eseo jasehi bol geoya, jigeum-eun jageun yese-reul bogo gabsida.

fun printLength(x: Any) {
    if (x is String) {
        println(x.length) // 예: 5
    } else {
        println("문자열이 아닙니다")
    }
}

fun main() {
    printLength("Hello")  // 5
    printLength(42)       // 문자열이 아닙니다
}

Yeogi-seo xneun bakke-seo-neun Anyjiman, if (x is String) an-eseoneun “마치 String 인 것처럼” boimnida. i geot-i smart cast-ui silje imnida.

4. Smart cast: keompailleo-ga “jache-eulo ihaehaejuge”, banghae-man an hamyeon

Smart cast-neun maji-ga anigo, silhaeng heuleum-e daehan jeonggyohan bunseok-imnida: keompailleo-neun yeoreobun-ui geomsa (is, != null, ilbu jogeon)reul bogo, “i branch-eseoneun gachi-ga jeoldae null i aniya” tto-neun “i branch-eseoneun jeoldae Stringiya”rago gyeollon naerimnida. Geu daeum myeongsi-jeogin byeonhwan eop-si-do deo 구체 tyip-cheoreom jeobge haejumnida.

K2 keompailleo-reul sseuneun Kotlin (Kotlin 2.0-buteo)eseoneun smart cast-ga ije deo maneun sanghwang-eseo ganeunghaeyo. Yep-eul deulmyeon, tyip geomsa-reul byeoldo-ui Boolean byeonsu-ro ppyeo nonda-eum, geu byeonsu-reul if jogeon-e seo sseuneun gyeongu.

Uri appcheoreom sanghwang-e seo yese-reul bopsida: eotteon command-ga 있고, “argument”reul jamkkan Anyro jeojanghae 둔다고 haebos죠 (테스트나 data source-ga dareun tyip-eul deonjyeojul su itgi ttaemunimnida).

fun normalizeAmount(raw: Any): Int? {
    val isText = raw is String
    if (isText) {
        return raw.toIntOrNull()
    }
    return null
}

Kotlin 2.x-eseoneun keompailleo-ga isTextwa “rawreul branch 안에서 Stringcheoreom bol su 있다”raneun yeongyeol-eul deo jal “bonda”go bol su itseumnida.

Smart cast-ga jal an doe-neun gyeongu

Eotteon sanghwang-eseoneun Kotlin-i jeongjik하게 malhamnida: “na-neun tyip-i an bakkwindaneun geos-eul 보장hal su eopseo.” Gajang jaju inneun gyeongu-neun, geomsa haneun dae상-i byeongyeong ganeun gachi-igo, geomsa-wa sayong saie gachi-ga bakkwil su issneun gyeongu입니다. Chobo gwajeong eseoneun ireoke malhal su its습니다: smart cast-neun valreul joaha고, varreul-neun byeollo joaha하지 않습니다.

Tto dareun jaju inneun 시나리오: mueon-ga-reul geomsahaetjiman, geu daeum eotteon dongjak-eul haeseo gachi-ga bakkwieosseul su itge doenda( tto-neun keompailleo-ga “bakkwieoji anassda”raneun geos-eul hwaksinha지 못한다) myeon, keompailleo-ga “hwaksin”eul daesi “chogihwa”ha고, daesi anjeonhan 호출 tto-neun myeongsi-jeogin byeonhwan-eul yoguhal su itsseumnida. Igeon gokeum-i anira boho imnida.

5. Anjeonhaji 않은 byeonhwan: as

Gakkeum-eun gachi-ga pilyohan tyip-ira-neun geos-eul hwaksin하나, Kotlin-ege myeongsi적으로 malhago sip-eul ttaega 있죠: “i geot-eul String 으로 bwara.” Geureol ttae sseuneun geos-i as yeonsanja imnida.

Munje-neun asneun geomsa-ga 아니라 tyip-eul ganging으로 baddeulyeoneun 시도라는 점입니다. tyip-i matji 않으면, peurogeuraem-eun silhaeng sigan-e ClassCastExceptioneuro keolligo jumuknida. 즉 keompailleo-neun kodeu-reul tonggwa시키지만, 오류는 silhaeng ttae nasseumnida.

Mini yese (goksu로 “wiheom하게”):

fun forceString(x: Any): String {
    return x as String
}

fun main() {
    println(forceString("OK")) // OK
    println(forceString(123))  // ClassCastException (실행 중)
}

Wae i geos-i jigeum jungyo할까요? asreul “un”euro sseugi sijak하는 gyeongu-ga jaju isse기 때문입니다: “ama munjayeol-in geot 같은데…” Geureoke 하면 안 됩니다. asneun jeongmal로 tyip-e dae한 “gyeoljeongjeogin 보장”i 있을 ttae joheumnida (yep: naega jikin gosi-ge Stringeul neoeotgo, dareun geot-eun jeoldae an neohneun gyeongu).

6. Anjeonhan byeonhwan: as? wa Elvis ?:

as?neun asui “부드러운 버전”입니다. Tyip-eul byeonhwanhae bogo, andoemyeon jumukji 않고 nulleul banhwan합니다.

I geos-eun nullable tyip-e daehae 지금까지 baeun naeyong-e 아주 jal eoul립니다: geu daeum null geomsa-reul 하거나, Elvis yeonsanja ?:reul sseumyeon doemnida.

Yese:

fun stringOrNull(x: Any): String? = x as? String

fun main() {
    println(stringOrNull("Hi")?.length) // 2
    println(stringOrNull(123)?.length)  // null
}

Deo sil용jeog-euro-neun, “gibon gachi”reul baro jwo beoril su itsseumnida:

fun stringLengthOrZero(x: Any): Int {
    val s = x as? String ?: return 0
    return s.length
}

fun main() {
    println(stringLengthOrZero("Kotlin")) // 6
    println(stringLengthOrZero(10))       // 0
}

Yeogi-seo neun geodeuro ilgi swip습니다: “munjayeol-lo byeonhwanhae bogo, an doemyeon 0.”

7. Yuyonghan tip: heodongiji ango gajang ganpyeonhage sseugi

is, as, as? bigyo

I 세 가지 ga gakkai nodeul ttae, chobo-ui dueneun botong jasin-eul norae han hwang-gi-gwan cheoreom yeonchulhamnida: “윙” 하고 sonenun amu geotdo an natanabnida. Chai-jeomeul gajang hyeonsiljeog-euro jeongrihaebopsida.

Gigu Mu-eot-eul hana Mu-eot-eul banhwan Tyip-i matji aneumyeon
x is T
tyip-eul geomsa
Boolean
geunyang false
x as T
tyip-eul byeonhwan
T
ClassCastExceptioneuro jumuk
x as? T
tyip-eul anjeonhage byeonhwan
T?
null banhwan

“Geu an-e mu-eot-i inneunji”reul il단 파악하고 sip-eumyeon isro sijakhaseyo. “Anjeonhage pilyohan tyip-eul sseul su inneunji sirheomhae bogo sipda”myeon as?. asneun “jeongmal 확신하고, geu hwaksin-e daehae chaegimjil su 있을 ttae” man name겨두세요.

wheneseo tyip bun-gi wa smart cast

Gakkeum-eun 여러 개의 if (x is …) dae신 wheneul sseoseo branch-by-tyip-eul chaek-haneun geot-i deo pyeonhamnida. Teukhi yesanghaneun data hyeongtae-ga 3–4gae jeongdo itgo, kkakeumhan “cheori pyob”reul mandeulgo sip-eul ttae yuyong합니다.

fun describeValue(x: Any): String =
    when (x) {
        is String -> "길이가 ${x.length}인 문자열"
        is Int -> "정수 $x"
        else -> "다른 값"
    }

fun main() {
    println(describeValue("Hi")) // 길이가 2인 문자열
    println(describeValue(7))    // 정수 7
}

Gak branch 안에서 xneun pilyohan tyip-euro smart cast doego, .lengthreul sse거나 suja-reul print 하myeon 됩니다. Wonri-neun ifwa ttokgatgo, pyeonhagi hyungtae-ga deo gan결하다는 jeom-man dareumnida.

8. Yese: Any?eseo jisul geumaek parsehagi

Siljeon kodeu-eseoneun “geunyang tyip-eul byeonhwanhae boryeo”ga mokjeog-in gyeongu-neun 드뭅니다. deae신 bori jom deo myeonghwakhan munje-ui ilbu입니다: ibryeok parse, gujo-eseo pildeu chulchul, dareun format cheori deung.

Uri gajyeongbu-e func-ga 있다고 haebopsida. i func-neun eotteon source-eseo “geumaek-ui raw gachi”reul bad습니다. Gan단han keonsol beojeon-eseoneun readln()eseo 온 Stringijiman, teseuteu-eseo func-reul bulleo Intreul neoeo jul su-do itsseumnida. Uri-neun Any?reul badeun dae, koppeikha 단위(jeongsu) geumaek-eul eod-eo bogo, bul가능하면 nulleul dollyeo jugeoneun bo편 handler-reul mandeulgo sip습니다.

fun parseAmountCents(raw: Any?): Int? {
    if (raw is Int) return raw
    val text = raw as? String ?: return null
    return text.trim().toIntOrNull()
}

fun main() {
    println(parseAmountCents(" 120 ")) // 120
    println(parseAmountCents(55))      // 55
    println(parseAmountCents("oops"))  // null
}

Yeogi-seo “siljeoncheoreom, hajiman gwajang eopsi” jal jeongri-doen point-reul bogo gyeseyo: meonjeo 빠른 경로: 이미 Int이면 끝. 그다음 as?로 munjayeol-eul anjeonhage ppae-om니다. munjayeol-i 아니면 — null. munjayeol-i 맞으면 — trim 하고 parse.

Jageun flowchart

flowchart TD
    A["raw: Any?"] --> B{raw is Int?}
    B -- yes --> C["return raw"]
    B -- no --> D{raw as? String}
    D -- null --> E["return null"]
    D -- String --> F["trim + toIntOrNull()"]
    F --> G["return Int?"]

Ireohan seukema-neun ijeonhagi joheun i유ga 있습니다: isneun tyip-e 따른 갈림길이고, as?neun jumuk 없이 pilyohan tyip-eul “kkeonae boryeo-neun 시도”임을 bo여 주기 때문입니다.

9. is, smart cast, as, as? sayong si jaju naneun silsu

Silsu 1: asreul “tyip geomsa”cheoreom sseugi.
Chobo-ga jaju 하는 saenggak: “asga an doemyeon — geureom tyip-i anin 거지.” Hajiman i gyeongu “an doenda”neun uimi-neun ClassCastExceptioneuro peurogeuraem-i jumukneundaneun geot입니다. Tyip-i daleul su itdamyeon — meonjeo is geomsa tto-neun anjeonhan as?reul 쓰고, asneun jeongmal 보장이 있을 ttae-man 남겨두세요.

Silsu 2: as?ga nullable (T?)reul banhwanhaneun geot-eul 잊기.
as?neun “순수한 tyip”eul 주는 게 아니라, “어쩌면 그 tyip”eul 줍니다. Geuraeseo val s = x as? String; println(s.length) cheoreom sseumyeon keompail-i an doemnida — geugeo-seo do joheumnida. ol바른 jeons개: s?.length, if (s != null), tto-neun gibon값-eul wihan Elvis ?:.

Silsu 3: keompailleo-ga 보장hal su eomneun gos-eseo smart cast-reul 기대하기.
Gachi-ga byeongyeong doegil su 있다면 (jaju varwa yeongyeol) keompailleo-ga smart cast-reul 거부할 su 있습니다. waenyahamnyeon “geomsa-wa sayong 사이에” object-ga 이론적으로 dareun geot-euro bakkwil su 있기 때문입니다. Igeon teul-eot da-gi가 아니라 anjeon장치입니다. i런 gyeongu-neun 보통, geomsa-wa sayong-eul gakkai 붙이도록 kodeu-reul jaeguseong 하거나, ro컬 valeuro boksahae 그 gachi-e daehae jak업합니다.

Silsu 4: modu-reul neomu il찍 Anyro ilbanhwa하기.
Anyneun pyeonhallae bo일 su 있습니다: “hamseu hana-ro modu 처리.” Hajiman daega-ga 있습니다: geu gyeolgwaro tyip geomsa, when, as?ga geum방 natanago, kodeu-ga ilgi eoryeowojimnida. Gibon gyuchik: Anyneun jeongmal로 contract sang pilyohan gos (yep: yobeomhan parser/adapter)eseo-man ssego, geu bakke-neun hamseu parameter-e 구체 tyip-eul seontaekhaseyo.

Silsu 5: “tyip geomsa”wa “business logic”reul han 덩어리로 섞기.
if (x is String) an-eseo 40줄 business logic-eul sseugi sijakhamyeon, kodeu-ga geum방 ilgi himdeureojimnida. Deo na-eun bangbeop: jageun block-eseo tyip-eul kkakkumhage byeonhwanha거나 (tto-neun 오류/null banhwan), geu daeum-eun jeong상 tyip String/Intro jeong리된 data-reul 가지고, 매번 검사를 반복하지 않는 명확한 도메인 로직-eul sseuneun geot입니다.

1
과제
Kotlin SELF, 레벨 34, 레슨 3
잠금
레이블 검사
레이블 검사
1
과제
Kotlin SELF, 레벨 34, 레슨 3
잠금
첫 글자
첫 글자
1
과제
Kotlin SELF, 레벨 34, 레슨 3
잠금
표준 패스포트
표준 패스포트
1
과제
Kotlin SELF, 레벨 34, 레슨 3
잠금
제목 정규화
제목 정규화
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION