https://kotlinlang.org logo
#announcements
Title
# announcements
s

Sudhir Singh Khanger

07/15/2019, 4:10 AM
Copy code
if (nullableIntOne ?: 0 < nullableList?.size ?: 0) {
    // some code 1
} else {
    // some code 2
}
I can't compare nullable types. So what is the likelihood of above code breaking. How can I mitigate it?
j

Josh Feinberg

07/15/2019, 4:14 AM
define breaking?
s

Sudhir Singh Khanger

07/15/2019, 4:29 AM
🙂 throwing an exception or neither parts executing.
g

gildor

07/15/2019, 5:46 AM
make it non-nullable %)
Depends on case, but in general you just have to handle this case somehow
If you really have a lot of such cases, you of course can introduce compareTo operator for nullable int:
Copy code
operator fun Int?.compareTo(other: Int?): Int {
    val a = this ?: 0
    val b = other ?: 0
    return a.compareTo(b) 
}
But I wouldn’t recommend to do that! Because this
0
is not universal default, what should be bigger -1 or null?
one more solution, just introduce private function that compare 2 nullable int, but with some semantics, not just universal comparasion function
s

Sudhir Singh Khanger

07/15/2019, 9:08 AM
Thanks. I will look into the solutions you have suggested.
2 Views