Kotlin Bootcamp for Programmers: constructor

OvO·2020년 7월 15일
0
post-thumbnail

Default

class Aquarium(length: Int = 100, width: Int = 20, height: Int = 40){
    val length = length
    val width = width
    val height = height
}
///////// 조금 더 개선
class Aquarium(var length: Int = 100, var width: Int = 20, var height: Int = 40){
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
}

lenth, width, height가 아닌 numberOfFish값으로 클래스를 만들어야 할 때가 생길 수 있는데 이는 현재코드로서는 불가능하다. 그래서 constructor 키워드를 사용해서 이때의 문제를 해결할 수 있다.

Secondary constructor

class Aquarium(length: Int = 100,var width: Int = 20,var height: Int = 40) {

    var length = length
    var volume: Int
        get() = width * height * length / 1000  //단일표현식
        set(value) {height = (value * 1000) / (width * length)}//관례적으로 setter의 매개변수이름은 value이다
    var water = volume * 0.9
    constructor(numberOfFish: Int): this(){ //this()로 primary constructor(클래스 선언과 동시에 만들어진 생성자)를 호출
        val water: Int = numberOfFish * 2000
        val tank = water + water * 0.1
        height = (tank / (length * width)).toInt()
    }
}

constructor키워드를 활용하여 secondary constructor (constructor(numberOfFish: Int))를 정의하여 numberOfFish의 값이 들어올 경우를 해결하였다.
좋은 kotlin code는 하나의 생성자만 있어야 하지만 secondary constructor를 사용할 시 this를 활용해서 primary constuctor를 호출해줘야한다.

Init

//init박스는 위에서 아래로 실행됨.
//이때 보조 생성자를 호출할 경우 보조생성자에서의 생성자 리스트가 실행되고 다음 init으로 넘어감
//모든 init을 실행한다음에서 보조생성자 내부가 실행됨
class Fish(val friendly: Boolean, volumeneeded: Int){
    val size: Int
    init{
        println("first init block")
    }

    constructor(s: String): this(true, 10){
        println("running second")
    }

    init{
        if(friendly){
            size = volumeneeded
        }else{
            size = volumeneeded * 2
        }
    }
    init{
        println("constructed fish of size $volumeneeded final size $size")
    }
    init{
        println("Last init block")
    }
}
profile
이유재입니다.

0개의 댓글