ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [코틀린] 생성자
    카테고리 없음 2024. 3. 15. 10:06

    Primary Constructor

    클래스는 하나의 primary constructor와 여러 개의 secondary constructor을 가질 수 있다.

    class Country constructor(displayName: String)
    
    // 아래처럼 constructor 키워드에 접근 제한자가 없다면 축약하여 적을 수 있다.
    class Country(displayName: String)

     

    primary constructor에선 코드를 실행할 수 없다.

    만약 코드를 실행하고 싶다면 init 블럭을 이용하면 된다.

    (굳이 아래처럼 만들지 않고 주석처럼 만들면 되지만 init 블럭 예시로 보여준 것이다.)

    class Country(displayName: String) {
    
        private val length: Int // private val length = displayName.length
    
        init {
            length = displayName.length
        }
    }

     

    primary constructor에 있는 변수는 var이나 val을 붙인다면 필드뿐만 아니라 함수에서도 사용할 수 있다.

    class Country(
        displayName: String,
        private val money: Int
    ) {
    
        private val length = displayName.length // o <- 접근 가능
    
        fun showInfo() {
        	println("국가 이름은 ${displayName}입니다.") // x <- 접근 불가
            println("국고엔 ${money}원이 있습니다.") // x <- 접근 가능
        }
    }

    Secondary Constructor

    클래스에 constructor 블럭을 적어서 여러개의 constructor을 가지게 할 수 있다.

    class Country {
    	
        private val displayName: String
        
        constructor(displayName: String) {
            this.displayName = displayName
        }
    }

     

    만약 primary constructor를 가지고 있다면 secondary constructor는 this() 생성자를 이용하여

    primary constructor에 생성을 위임해야 한다.

    class Country(displayName: String) {
    	
        private val money: Int
        
        constructor(displayName: String, money: Int) : this(displayName) {
            this.money = money
        }
    }

     

Designed by Tistory.