

보조 생성자
예시)
//보조 생성자 선언
class ConstructorLearn{
constructor(name: String){
println("contructor(name: String) call..")
}
constructor(name: String, count: Int){
println("contructor(name: String, count: Int) call..")
}
}
fun main() {
val user1 = ConstructorLearn("Stef1")
val user2 = ConstructorLearn("stef2",10)
}
보조 생성자에 주 생성자 연결
코틀린의 생성자는 주 생서자와 보조 생성자로 나눈다
만약 주 생성자와 보조 생성자 모두 선언한다면 반드시 생성자끼리 연결해 주어야 한다
▪ 예) 주 생성자와 보조 생성자 선언하고 연결 없으면….
class User(name: String){
constructor(name: String){ //=> 오류!! 반드시 주랑 보조 사용하면 연결해야함!
.....
연결한 예시)
class bothConstructor(name: String) {
constructor(name: String, count: Int):this(name) {
println("bothConstructor(name: String) and constructor(name: String, count: Int):this(name)....")
}
}
보조 생성자 선언부에 this(name)만 추가한 코드이다!
▪ 이렇게 하면 보조 생성자와 함께 호출된다!
반드시 어떤 식으로도 주 생성자가 호출되게 해야한다
만약 주 생성자가 있고 보조 생성자가 여러 개 선언하면….
▪ 어떻게든 주 생성자가 호출되게 해야 한다