Why Setter doesn't work?

_qua = -3 = <0, may i know why it doesn’t return 0?
Thanks for the help!

class Food(val name: String, _qua: Int){
    var qua = _qua
    set(value){
        field = if(value > 0) value else  0
    }
}

fun main(){
    val food1 = Food("Coco", -3)
    print("Food name: ${food1.name}, quantity: ${food1.qua}")
}

Output:
Food name: Coco, quantity: -3

Setters are not called on field assignments var qua = _qua. Consider calling the setter via init instead:

class Food(val name: String, _qua: Int){
    var qua = 0
    set(value){
        field = if(value > 0) value else  0
    }

    init {
       qua = _qua
    }
}
2 Likes

You’re not invoking the setter in your code, you’re just initialising the value of qua to -3.
And yes - setting something at class initialization doesn’t go through the setter logic even if one is present.

2 Likes

Thanks for the advice & explanation!

may i know should I always use init block in similar case? or any other simpler ways?

Thanks!

1 Like

It really depedns on what your setter does.
If you’re ignoring a negative value - instead of using 0 - then it’s unclear what is the init approach is, you could just throw in init instead, but fundamentally is a chioce you need to make each time.

2 Likes

if i change the main code as follows (class Food unchanged, without init), it works and output is 0.
may i know what’s the difference? why init is not required in this case?
Thank you for the effort!

fun main(){
    val food1 = Food("Coco", -3)
    food1.qua = -8
    print("Food name: ${food1.name}, quantity: ${food1.qua}")
}

Here

you’re setting the var hence running the setter. What did you expect to see?

2 Likes