Kotlin’s equality operators (== and !=) can handle nulls, while the order comparison operators (<, <=, >, >=) can’t.
You have to check the nullability before doing the comparison.
You may also use another value if the live data is null (like 0) using the Elvis operator, but I won’t suggest this solution, because the null value is not the same as the zero value.
The live data values are nullables, so you can’t do that comparison. From the androidX LiveData java class:
@Nullable
public T getValue() {
Object data = mData;
if (data != NOT_SET) {
return (T) data;
}
return null;
}
The @Nullable annotation tells Kotlin that has to make the value nullable. That is why the errors says
Required Int
Found Int?
val adderValue = _adder.value //this is nullable
val quantityValue = _quantity.value //this is nullable
For fixing your problem you have to decide what to do with null.
If you want that null to be equivalent to zero, then:
_adder.value ?: 0 < _quantity.value ?: 0
Or if is null, then nothing should happen, then:
val adderValue = _adder.value ?: return
val quantityValue = _quantity.value ?: return
if (adderValue < quantityValue)
Since you are adding a cupcake I speculate what you want is the following:
val adderValue = _adder.value ?: 0 //no additions before so is ok
val quantityValue = _quantity.value ?: return //null quantity is not ok, error we stop
if (adderValue < quantityValue) {
_adder.value = adderValue++
}
What you are doing there _adder.value?.plus(1) is not updating the live data value.
2
Answers
Kotlin’s equality operators (== and !=) can handle nulls, while the order comparison operators (<, <=, >, >=) can’t.
You have to check the nullability before doing the comparison.
You may also use another value if the live data is null (like 0) using the Elvis operator, but I won’t suggest this solution, because the null value is not the same as the zero value.
The live data values are nullables, so you can’t do that comparison. From the androidX LiveData java class:
The
@Nullable
annotation tells Kotlin that has to make the value nullable. That is why the errors saysFor fixing your problem you have to decide what to do with
null
.If you want that null to be equivalent to zero, then:
Or if is null, then nothing should happen, then:
Since you are adding a cupcake I speculate what you want is the following:
What you are doing there
_adder.value?.plus(1)
is not updating the live data value.