_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}")
}
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.
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.
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}")
}