What is the right way of using "greater than", "less than" comparison on nullable integers in Kotlin?
var age : Int? = 0
public val isAdult : Boolean?
get() = age?.let { it >= 18 }
The other solution would be using delegates:
var age : Int by Delegates.notNull()
public val isAdult : Boolean
get () = age >= 18
So if you try to get age or check isAdult before age was actually assigned then you'll get exception instead of null.
Anyway I believe age = 0 is some kind magic that one day may lead to issue (even prod issue).
Kotlin could sure use an extension function on Int
for this, but until they do:
fun Int?.isGreaterThan(other: Int?) =
this != null && other != null && this > other
fun Int?.isLessThan(other: Int?) =
this != null && other != null && this < other
My methods returns false
, not null
if either operand is null
. That makes more sense to me.