언어/Kotlin

Kotlin : Setter 와 Getter 1.5

해리누나 2022. 10. 12. 21:48
728x90
반응형

get 메서드와 set 메서드를 이용해 저번에 적은 코드(https://bruders.tistory.com/34)를 좀 다듬어보자.

 

class Glass(content_param: Int, val capacity: Int){

    constructor(part: Double, capacity: Int): this((part*capacity).toInt(), capacity)

    var drink = "water"
    set(value){
        field = value.toUpperCase()
    }

    var content = content_param
    set(value){
        if(value < 0 ) field = 0
        if(value > capacity) field = capacity
        if(value in 0..capacity){
           field = value
        }
    }
    get(){
        return field
    }
    init{
        content = content_param
    }

    fun readContent(){
        println("잔 내 액체의 양은 $content ml입니다.")
        println("잔 내 최대 허용 액체의 양은 $capacity ml입니다.")
    }

    fun calculateAmount(): Int {
        return this.capacity - this.content
    }

    fun pour(wishAmount : Int){

        if(wishAmount < calculateAmount()){
            this.content += wishAmount
        }
        else {
            this.content = capacity
        }
    }
}


class Bottle (var content: Int){

    fun pourIntoGlass(glass : Glass) {
        
        var possibleAmount = glass.calculateAmount()

        if (this.content < possibleAmount) {
            possibleAmount = this.content
        }
        this.content -= possibleAmount
        glass.pour(possibleAmount)

    }

    fun readContent(){
        println("병 내 액체의 양은 ${this.content} ml입니다.")
    }
}


fun main(){

    val glass0 = Glass(0,100)
    val glass1 = Glass(90,150)
    val bottle = Bottle(30)
    
}

 

- content_param은 하나의 속성이 아니라 속성 'content'의 초기화를 위해 사용되는 것일 뿐이다.

- init은 set과 마찬가지로 변수 뒤에 써있어야 한다. 여기서 init을 써 준 이유는

init을 해줘야만 초기값에도 set메서드가 적용이 되기 때문.

 

 

 

출처:

내용 / 도움준 곳: 학교 교수님 (Christian Kohls) 강의

728x90
반응형

'언어 > Kotlin' 카테고리의 다른 글

Kotlin : 간단한 for 과 while, do..While 문의 이용  (0) 2022.10.13
Kotlin : 리스트 (list)  (0) 2022.10.12
Kotlin : Setter 와 Getter  (0) 2022.10.12
Kotlin : 중간점검  (1) 2022.10.11
Kotlin : ArrayList (배열 + 리스트)  (0) 2022.09.07