kotlin constructor

22·2024년 7월 10일

Kotlin

목록 보기
1/1

Primary Constructor

  • 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

Secondary Constructor

  • prefix 로 constructor 를 사용해야한다.
  • 기본 생성자가 있는 경우는 this를 사용하여 위임해야한다.
  • init 은 기본 생성자의 일부이기 때문에, secondary constructor 이전에 실행된다.
class Constructors {
    init {
        println("Init block")
    }

    constructor(i: Int) {
        println("Constructor $i")
    }
}
Init block
Constructor 1
  • primary constructor 가 없더라도 먼저 실행된다.

REFERENCE

https://kotlinlang.org/docs/classes.html#class-members

0개의 댓글