오늘 문득 업무를 하다가 갑자기 궁금해진 것…
Kotlin 은 constructor 와 init 두 가지를 통해 객체를 생성할 수 있는데
“만약 동시에 두가지 모두 사용할 경우에
어떤 함수가 먼저 호출이 될까??”
갑자기 궁금해져서 테스트를 해보았다
아래는 테스트를 하면서 작성한 코드이다
1class Person(private val name: String) { //primary constructor2 private var age: Int = 03 set(value) {4 println("property called")5 field = value6 }7 private lateinit var address: String8 private lateinit var company: String910 constructor (name: String, age: Int, address: String) : this(name) { //secondary constructor11 println("constructor 1 called")12 this.age = age13 this.address = address14 }1516 constructor (name: String, age: Int, address: String, company: String) : this(name) { //secondary constructor17 println("constructor 2 called")18 this.age = age19 this.address = address20 this.company = company21 }2223 init {24 println("init called")25 if (!::address.isInitialized)26 this.address = "unknown address"27 if (!::company.isInitialized)28 this.company = "unknown company"2930 }31}
여기서 객체를 생성하게 되면 결과는 다음과 같다
1val reno = Person("Reno", 31, "Seoul", "KM")23/**4 * result5 *6 * init called7 * constructor 2 called8 * age called9 * */
즉, 다음의 순서로 호출이 된다 !
- init method
- constructor
- property