1. Sogae
Chogihwa sunseo-neun yori hal ttae-ui sunseo-wa gateumnida: meonjeo keikeu-reul oven-e neohgo, geuttae seo-ya banjuk-i ajik bongji an-e itda-neun geoseul tteoolimyeon… geolgug “silheomjeok” yori-ga doemnida. Programing-eseo-do gachi: init an-eseo ajik chogihwa doegi jeon-ui peuropeoti-reul sayonghageona, secondary constructor bonmun-i “data-reul junbihal sigani itgetji”rago saenggakhaneun sungan, isanghan gap, bulpilyohan yeonsan, tteoneun yesangchi moshan goseoseo-ui yekoe-reul mannage doemnida.
I gang-ui mokjeok-eun yeoreobun-i da-eum-gwa gateun jilmun-e daehayeo hwaksilhage daedaphal su itge haneun geot-imnida: eotteon println() i dareun geotboda meonjeo chulryeokdoeneunji, wae geomsa-ga secondary constructor bonmun-ui na-eui kodeu boda meonjeo baldongdoeneunji, wae init an-eseo peuropeoti-ga beolsseo gap-eul gajigo itneunji, geurigo eotteon gyeosan-eul eodie du-eoya 딱 han beon, geurigo olbareun ttae-e silhaengdoeneunji-ibnida.
2. Mentaleu modeul: gaekche saengseong-eun mueos-ro guseongdoeneunga
Uriga val e = Expense(...) reul sseumyeon han jullocheoreom boimnida. Hajiman silje-ro gaekche saengseong-eun yeore step-euro irueojin sikeonjwa gatgo, Kotlin-eun i deul-eul 고jeongdoen sunseo-ro silhaenghamnida. Ireul gajang pyeonhage badadeul-inun bangbeop-eun jageun “컨베이어”reul tteoolineun geot-imnida: meonjeo peuropeoti-reul junbihago (chogihwaja), geu daeum init-beullokdeul-i silhaengdoego, geurigo geu hu (secondary constructor reul tonghae saengseonghal ttae man) geu bonmun-i silhaengdoemnida.
Haesim-eun i렇습니다: init-beullokdeul-eun 인스턴스 saengseong si silhaengdoemyeo, peuropeoti chogihwaja-cheoreom sunseo-daero jinhaengdoemnida. Geurigo secondary constructorinit) ga secondary constructor
Seukema-reul hwaksilhi haebopsida.
flowchart TD
A["Saengseongja 호출: ClassName(...)"] --> B["Primary constructor 로 delegeting (필요 시)"]
B --> C["Peuropeoti chogihwaja (keullaeseu an-eseo seon-eon sunseo-daero)"]
C --> D["init-beullok (keullaeseu an-eseo seon-eon sunseo-daero)"]
D --> E{"Secondary constructor 로 saengseonghaetna?"}
E -->|ye| F["Secondary constructor bonmun { ... }"]
E -->|aniyo| G["Gaekche junbi wanryo"]
F --> G
Nun-euro baro hwaginhal su itdorok jjalbeun pyo-do chugahamnida:
| Keullaeseu bu-bun | Eodieseo sseuneunga | Eonje silhaengdoeneunga |
|---|---|---|
| Peuropeoti chogihwaja | |
init bo다 meonjeo, keullaeseu an seon-eon sunseo-daero |
| init { ... } | |
Peuropeoti chogihwaja hu, yeoksi wi-eseo araero sunseo-daero |
| Secondary constructor bonmun | |
Peuropeoti + init i kkeutnan hu |
Tto hanae-ui yuyonghan gireumgireun: primary constructorinit-beullok boda meonjeo il-eonaneunda-go bol su itseumnida. Geuraeseo “han jul”cheoreom boijiman, silje step-eun manh습니다.
3. Peuropeoti chogihwaja: saenggakboda deo ireun ttae-e silhaengdoenda
Peuropeoti chogihwaja-neun peuropeoti seon-eon si = o-reun쪽-e inneun pyohyeonshik-imnida. Bo기에-neun dan순히 “gap-eul jeonghaetda” cheoreom 보ijiman, uimijeok-euro-neun gaekche saengseong jung silhaengdoeneun kodeu jo각-imnida. Geuraeseo chogihwaja-reul guchuk gwajeong-ui ilbu-ro deryeoga야 합니다: dan순하고, 예측 가능하며, gaekche saengseong-eul 12-gyejeol 드라마로 mandeulji aneumyeon jo습니다.
Cho보ja-ga gajang 자주 gyesok mandeuneun nollam: “Nan meonjeo init i silhaengdoego, geu daeum peuropeoti-ga chogihwadoel georago saenggakhaesseo.” Silje-ro-neun ban대입니다: peuropeoti chogihwaja-ga init boda meonjeo silhaengdoemnida. I geos-eulo init an-eseo (kodeu sang-e wi-e seon-eon doeeo itgo, “wiheomhan” geot-e u존haji anneun dan) i peuropeoti deul-ui gap-eul 비교적 안전하게 sayonghal su itge doemnida.
Constructor pparamiteo-e 의존하는 peuropeoti
Gyoyuk-yong 콘솔 mini-peurojekteu “jichul gwanri” (gaseong-ui ExpenseTracker) reul 계속haebopsida. Oneul-eun chogihwa sunseo-reul bo여 ju-neun 모델 ilbu-reul mandeul geos-imnida.
class Expense(rawTitle: String, val amountCents: Int) {
val title: String = rawTitle.trim()
val titleLength: Int = title.length
init {
println("init: title='$title', length=$titleLength")
}
}
fun main() {
Expense(" Coffee ", 350)
// init: title='Coffee', length=6
}
Yeogi-seo haesim-eun titleLength ga title e u존하고, title eun primary constructor pparamiteo rawTitle e u존haneun geot-imnida. Kotlin-eun i-reul munje eobsi 허용합니다: primary constructorinit an-eseo-do sayong hal su itseumnida.
Gaekche saengseong si meonjeo title i gyeyonsandoego, geu daeum titleLength, geurigo 나서 init i silhaengdoemnida. 즉, sunseo-neun keullaeseu bonmun-e sseuyeo itneun dae로 (wi-eseo araero) jinhaengdoemnida: sseuyeo itneun geudaero silhaengdoenda-go 보면 됩니다.
Peuropeoti chogihwaja-e sumgyeojin jakeob
Munje-neun peuropeoti chogihwaja-ga dan순히 su/munja-yeol-eul gyeyonsanhaneun geos-eul neomeoseo, “bu작용-i inneun” il-eul hal ttae sijakdoemnida: chulryeok, pa-il jeopgeun, 네트워크 jeop속 (ne, geureohge-do ham), tteoneun ajik junbi doji anheun mueon-ga-e u존haneun gyeongu-imnida.
Sunseo-reul bo-gi wihae ilbus러 “sikkeureopge” chogihwa haebopsida:
class DebugExpense(val rawTitle: String) {
val title: String = normalizeTitle()
init {
println("init: title='$title'")
}
private fun normalizeTitle(): String {
println("property init: normalizeTitle()")
return rawTitle.trim()
}
}
fun main() {
DebugExpense(" Taxi ")
// property init: normalizeTitle()
// init: title='Taxi'
}
Juuihaeseo boseyo: meonjeo normalizeTitle() eseo-ui chulryeok (i geos-i peuropeoti title ui chogihwaja-imnida), geurigo 나서 init eseo-ui chulryeok-i na옵니다. I geos-i 바로 “컨베이어 메커니즘”입니다.
init i “chogihwa-ui ju-yeok”iran saenggak-e 익숙하다면, ne: 중요합니다. Hajiman peuropeoti chogihwaja-do yǒn-yeolhan “silje chogihwa kodeu” ui ilbu-이며, dan지 gyae-ji an-go bo이지 않을 뿐입니다.
4. init-beullok: mo-a서 jeomgeomhagi
init-beullok-eun gaekche saengseong si silhaengdoeneun kodeu로, chogihwa-ui ilbu입니다. Bo통 du 가지 용도로 sayong합니다: 상태 정규화/준비, geurigo iblyeog yuhyo-seong geomsa.
Kotlin-eun yeoreo 개-ui init-beullok-eul gajil su itgo, geudeul-eun peuropeoti chogihwaja-wa hamkke keullaeseu bonmun-e seo-ro 나타난 sunseo-daero silhaengdoemnida. 말은 쉽지만, silje kodeu-eseo-neun jaju ireon jilmun-i na옵니다: “init-beullok-i yeoreo gae-myeon eoneu geot-i meonjeo?” tteoneun “peuropeoti-reul arae-e seon-eonhaetneunde, wi-eseo sayonghal su itna?” 같은 것들이죠. println() 로 namneun “흔적”eulo hwaksilhi bongyeobopsida.
Han gae-ui init wa chulryeok “흔적”
Cho-sohan “sunseo tracker” reul mandeureobopsida:
class BuildOrder(val x: Int) {
val y: Int = x + 1
init {
println("init: x=$x, y=$y")
}
}
fun main() {
BuildOrder(10)
// init: x=10, y=11
}
Yeogi-seo y ga init e 진입할 ttae 이미 gyeyonsandoeeo itneun geos-eul 볼 수 있습니다. 예측한 대로입니다: peuropeoti chogihwaja-ga meonjeo imnida.
Yeoreo gae-ui init-beullok: wi-eseo araero sunseo
Ibeon-eun init-beullok du gae-reul mandeulgo, geu sai-e peuropeoti han gae-reul 넣어봅시다. I geos-eun sunseo-ga “teksuteu” (파일에서 보이는 순서) daero라는 geoseul ches감hagi-e 아주 좋은 방법입니다.
class ManySteps(val name: String) {
init {
println("init #1: name='$name'")
}
val upper: String = name.uppercase()
init {
println("init #2: upper='$upper'")
}
}
fun main() {
ManySteps("Ann")
// init #1: name='Ann'
// init #2: upper='ANN'
}
실무적 결론은 단순합니다: 두 번째 init 이 어떤 peuropeoti 에 의존한다면, 그 peuropeoti 가 반드시 그 위에 선언되어 있어야 합니다. 그렇지 않으면 접근 자체가 불가능하거나, 읽기/유지보수가 어려운 구조가 됩니다.
5. Secondary constructor: wae bonmun-i hangsang majimak-in-ga
Secondary constructor
Cho보ja-neun 가끔 secondary constructorinit i silhaengdoel georago 기대합니다. Hajiman Kotlin-ui 계약은 다릅니다: secondary constructorconstructorthis(...)) 해야 하며, peuropeoti chogihwaja 와 init-beullokdeul-i 모두 kkeutnan hu-e야 secondary constructor
I geos-eun keullaeseu-ga han beon-ui 일관된 chogihwa 경로를 가지게 하려는 설계입니다: gaekche-ga “ban쯤 chogihwa된” 상태로 존재하면 안 되니까요.
Primary 로 delegeting: saengsaenghan yeje
Expense e secondary constructor
class Expense(val title: String, val amountCents: Int) {
init {
println("init: title='$title', amount=$amountCents")
}
constructor(rawTitle: String, amountText: String) : this(
title = rawTitle.trim(),
amountCents = amountText.toIntOrNull() ?: 0
) {
println("secondary body: amountText='$amountText'")
}
}
fun main() {
Expense(" Tea ", "120")
// init: title='Tea', amount=120
// secondary body: amountText='120'
}
init eseo-ui 메세지-ga secondary constructorconstructor
그것이 합리적이기도 합니다: init 은 gaekche “정합성”의 핵심 경로입니다. Secondary 가 먼저 실행될 수 있다면, 일시적으로라도 gaekche 를 잘못된 상태로 둘 수 있게 되니까요.
Primary ga eomneun keullaeseu: init eun geuraedo secondary bonmun boda meonjeo
Gakkeum primary constructorinit 이 마치 constructor 뒤에 오지 않을까?”라고 생각하기 쉬운데, 그렇지 않습니다. init-beullok-eun 여전히 secondary constructor
class NoPrimary {
init {
println("init runs first")
}
constructor(x: Int) {
println("secondary body: x=$x")
}
}
fun main() {
NoPrimary(5)
// init runs first
// secondary body: x=5
}
I geos-eul gieokhae dumyeon “un-eul gidarigi”reul meomchugo, chogihwa-reul 의식적으로 설계하게 됩니다: 올바름을 위해 필요한 모든 것은 공통 경로에 두고, secondary constructor 는 입력을 맞추는 어댑터(그리고 많아야 로그 같은 부수 작업)로 남겨두되, 기본 상태를 만드는 장소로 쓰지 않습니다.
6. Mini app (jichul gwanri) eseo na올 su inneun “surprise”
Ije mekeonijeum-eul silje 의미에 yeongyeol해 봅시다. 콘솔 ExpenseTracker 에서 우리는 Expense 가 항상 올바르기를 원합니다: 제목은 비어 있지 않고, 금액은 음수가 아니며, 목록 표시를 위한 “짧은 이름”도 편하게 저장하고 싶습니다.
Gyesan-eul eodie-e nwo야 할지 잘못 나누면, 중복, constructor 에 따라 달라지는 값, 혹은 읽기 어려운 혼란스러운 코드가 나올 수 있습니다. 아래 예제들은 약간 “교재용”으로 보이겠지만 의도적입니다: 비즈니스 로직이 아니라 “이벤트 순서”를 보여주기 위함입니다.
Silpae: secondary constructor ga init eul wihae data-reul junbihaejul georago 기대하기
init 에서 title 을 검사하고, secondary constructor
class BadExpense(val title: String) {
init {
require(title.isNotBlank()) { "title must not be blank" }
println("init: ok")
}
constructor(rawTitle: String, allowBlank: Boolean) : this(rawTitle) {
// Neujeotda! init i beolsseo jinaetda.
println("secondary body: allowBlank=$allowBlank")
}
}
BadExpense(" ", true) reul mandeulmyeon, require(...) i secondary constructorinit 은 공통 경로의 일부이기 때문입니다.
Yeogi-seo-ui olbareun saenggak-eun i geot입니다: iblyeog-eul “고쳐야” 한다면, delegeting sigjeom : this(...) (즉 init 으로 들어가기 전) 에서 하거나, 공통 경로의 peuropeoti chogihwaja / init
Olbareun pattern: init jeon-e iblyeog-eul junbi하기
“정상” 버전을 만들어봅시다: secondary constructor
class Expense(val title: String) {
init {
require(title.isNotBlank()) { "title must not be blank" }
println("init: title='$title'")
}
constructor(rawTitle: String, trim: Boolean) : this(
title = if (trim) rawTitle.trim() else rawTitle
)
}
fun main() {
Expense(" Taxi ", trim = true)
// init: title='Taxi'
}
Ije gaekche-reul eotteon 경로로 saengseonghadeun, init 은 hangsang 이미 junbi된 title eul 봅니다. I geos-eun “secondary = 어댑터, primary+init = 단일 공통 경로”라는 아이디어와 일치합니다.
Sunseo-reul API dizain 도구로 쓰기
Sunseo-reul ihaehage 되면, 로직을 eodie du-eoya 할지 선택하기가 훨씬 쉬워집니다.
Gyesan-i 딱 한 번만, 그리고 늘 같은 방식으로 이루어져야 한다면, delegeting pparamiteo (: this(...)) 에 두거나, peuropeoti chogihwaja-e 두거나, init 에 두는 것이 편합니다. I 세 위치는 모두 secondary constructor
Banh면, 어떤 동작이 gaekche 의 정합성에 영향을 주지 않는다면 (예: “문자열에서 지출을 생성했다”는 로그 출력), 그건 secondary constructor
Chogihwa reul 디버깅하는 방법
Chogihwa sunseo-ga hontongdoemyeon, du뇌는 “아마도 이럴 거야”를 그려내고, geulgwa 함께 유령 같은 원인을 쫓게 됩니다. 그래서 최고의 방법은 순서를 “보이게 만드는 것”입니다.
Gajang dan순한 도구는 peuropeoti chogihwaja, init, secondary constructorprintln() 을 넣는 것입니다. 메세지는 서로 구분되게 써야 합니다. 그렇지 않으면 나중에 로그를 암호문처럼 읽게 됩니다.
Tto 하나의 좋은 습관은 최소 예제를 만드는 것입니다: 클래스 하나, 프로퍼티 하나, init 하나, secondary constructorinit
7. Chogihwa sunseo ihae-eseo jaju nareuneun typijeok silsu
Silsu 1: init i peuropeoti chogihwaja boda meonjeo silhaengdoel georago 기대하기.
Heurihan 논리로는 “init eul sseosseunikka geogiseo sijakhagetji”라고 느낄 수 있습니다. Hajiman val x = ... 자체도 chogihwa kodeu이고, init 보다 meonjeo silhaengdoemnida. 그래서 어떤 사람들은 왜 어떤 계산/출력이 “constructor 보다 먼저” 일어나는지 놀라곤 합니다. 올바른 습관은 peuropeoti chogihwaja 를 gaekche saengseong-ui 1단계로 보고, init 보다 앞선다고 받아들이는 것입니다.
Silsu 2: secondary constructorinit
특히 secondary constructorinitinitconstructorinit: this(...) 안에서 처리하세요.
Silsu 3: peuropeoti chogihwaja-e mugeoun jakeob-eul sumgyeo nohgo, 성능/로그에 놀라기.
Peuropeoti chogihwaja-neun haldangcheoreom bo이기 때문에, geu 안에 bu작용이 있는 계산을 넣는 경우가 있습니다: 출력, 복잡한 문자열 파싱, 큰 객체 생성 등. 그러면 객체가 “생성 비용이 너무 비싸지고”, 로그에는 “저절로” 메시지가 넘쳐납니다. Peuropeoti chogihwaja 는 가능한 단순하게 유지하세요: 이미 사용 가능한 데이터로부터 놀라움 없이 값을 계산하고, 더 눈에 띄는 로직은 명시적으로 init (또는 primary 로 넘기기 전) 에 두는 편이 좋습니다.
Silsu 4: 코드에 나타난 순서와 머릿속 논리적 순서를 혼동하기.
두 번째 init 이 아래에 선언된 프로퍼티를 사용하려 하면, 컴파일러가 허용하지 않거나 코드를 무작정 재배치하게 됩니다. 도움이 되는 규율은 이렇습니다: 필요한 순서대로 프로퍼티를 선언하고, init-beullok은 의미를 보장하는 프로퍼티 근처에 배치하세요. Kotlin 은 init-beullok을 위에서 아래로 실행하며, 이는 “구현 디테일”이 아니라 가독성의 일부입니다.
Silsu 5: yeoreo constructor 에서 chogihwa/geomsa reul jungbok하기.
Keullaeseu-e secondary constructor 가 여럿이면, 초보는 종종 같은 require(...) 또는 같은 trim() 을 각 constructor 본문에 복사합니다. 결과: 한 constructor 를 업데이트하는 것을 잊으면, 생성 방식에 따라 클래스 동작이 달라집니다. 훨씬 신뢰할 수 있는 방법은 정합성 규칙을 공통 경로(init 및/또는 primary 로의 delegeting) 에 두어, 모든 생성 경로가 같은 로직으로 수렴하게 만드는 것입니다.
Silsu 6: gaekche saengseong-eul bu작용 “공연”으로 만들기.
Saengseong gwajeong-eseo 출력도 하고, 계산도 하고, 외부 변수도 바꾸고, 복잡한 시나리오도 실행하고 싶어질 수 있습니다. Hajiman gaekche saengseong-eun 최대한 “깨끗하게” 유지하는 것이 좋습니다: init 이 끝날 때 객체는 즉시 사용 가능한 상태여야지, “거의 됐고 세 단계만 더” 같은 상태여서는 안 됩니다. 외부 동작이 많이 필요하다면, 대개 “모델 생성”과 “애플리케이션 시나리오”를 한 곳에 섞어 넣은 신호입니다.
GO TO FULL VERSION