Navigate back to the homepage

Kotlin 의 constructor 와 init 중에 누가 먼저 호출될까?

Reno Kim
June 10th, 2020 · 1 min read

오늘 문득 업무를 하다가 갑자기 궁금해진 것…

Kotlin 은 constructor 와 init 두 가지를 통해 객체를 생성할 수 있는데

“만약 동시에 두가지 모두 사용할 경우에

어떤 함수가 먼저 호출이 될까??”

갑자기 궁금해져서 테스트를 해보았다

아래는 테스트를 하면서 작성한 코드이다

1class Person(private val name: String) { //primary constructor
2 private var age: Int = 0
3 set(value) {
4 println("property called")
5 field = value
6 }
7 private lateinit var address: String
8 private lateinit var company: String
9
10 constructor (name: String, age: Int, address: String) : this(name) { //secondary constructor
11 println("constructor 1 called")
12 this.age = age
13 this.address = address
14 }
15
16 constructor (name: String, age: Int, address: String, company: String) : this(name) { //secondary constructor
17 println("constructor 2 called")
18 this.age = age
19 this.address = address
20 this.company = company
21 }
22
23 init {
24 println("init called")
25 if (!::address.isInitialized)
26 this.address = "unknown address"
27 if (!::company.isInitialized)
28 this.company = "unknown company"
29
30 }
31}

여기서 객체를 생성하게 되면 결과는 다음과 같다

1val reno = Person("Reno", 31, "Seoul", "KM")
2
3/**
4 * result
5 *
6 * init called
7 * constructor 2 called
8 * age called
9 * */

즉, 다음의 순서로 호출이 된다 !

  1. init method
  2. constructor
  3. property

More articles from Reno

Android Accessibility

우아한 형제들의 Android Accessibility 적용 방식에 대한 글을 간단히 요약

June 5th, 2020 · 1 min read

HashMap vs HashTable

HashMap 과 HashTable 스터디하면서 정리한 글

February 27th, 2020 · 1 min read
© 2019–2021 Reno
Link to $https://github.com/renovatio0424Link to $https://www.linkedin.com/in/정원-김-33b30415a