primary constructor 에는 어떠한 code 도 들어갈 수 없다. 초기화하는 코드를를 넣고 싶은 경우 init() 을 사용해야한다.
kotlin init() 생성자와 property 선언 및 초기화는 같은 우선순위를 가져 위에서부터 선언된 순서대로 수행된다.
kotlin
class InitOrderDemo(name: String) {
val firstProperty = "First property: $name".also(::println)
init {
println("First initializer block that prints $name")
}
val secondProperty = "Second property: ${name.length}".also(::println)
init {
println("Second initializer block that prints ${name.length}")
}
}
First property: hello
First initializer block that prints hello
Second property: 5
Second initializer block that prints 5
init 은 기본 생성자의 일부이기 때문에, secondary constructor 이전에 실행된다. class Constructors {
init {
println("Init block")
}
constructor(i: Int) {
println("Constructor $i")
}
}
Init block
Constructor 1