The following functions produces error. How to use let() or similar null check functions inside a if/for statement.
Here is my code:
fun main() {
var List = listOf<Int>(201, 53 ,5 ,556 ,70 , 9999)
var budget: Int = 500
if(List.min() < 500) { // this line produces the error
println("Yes you can buy from this shop")
}
}
And here is the error:
Operator call corresponds to a dot-qualified call 'List.min().compareTo(500)' which is not allowed on a nullable receiver 'List.min()'.
Help me with nullable types. Thank you
The question here is: what do you want to happen if your list is empty?
If a list has one or more items, and those items are comparable, then you can always find a minimum. (It doesn't have to be unique.) But if the list has no items, then there is no minimum. So what do you want to happen then? Do you want to continue with a ‘default’ value? Or skip that block? Or something else?
If you want a default value, then you can use the elvis operator:
if ((list.minOrNull() ?: 0) < 500)
println("Yes you can buy from this shop")
That substitutes the value 0 if the list is empty. (It doesn't have to be zero; any value will do. In fact, this can work with any type as long as it's Comparable.)
Or you could do an explicit check for the list being empty:
if (list.isEmpty()) {
// Do something else
} else if (list.minOrNull()!! < 500)
println("Yes you can buy from this shop")
The !! non-null assertion operator works here, but it's a code smell. (It's easy to miss when you're changing surrounding code; it could then throw a NullPointerException.) So it's safer to handle the null. Perhaps the most idiomatic way is with let():
list.minOrNull().let {
if (it == null) {
// Do something else
} else if (it < 500)
println("Yes you can buy from this shop")
}
(The < check is allowed there, because by that point the compiler knows it can't be null.)
Or if you just want to avoid the check entirely, use a ?. safe-call so that let() is only called on a non-null value:
list.minOrNull()?.let {
if (it < 500)
println("Yes you can buy from this shop")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With