Optional primitive arithmetic & comparison


#1

Often I find I need to do math with optional ints:
if (someOptionalIntExpression > 0)

Of course those types don’t match. So I could write:
if (someOptionalIntExpression != null && someOptionalIntExpression > 0)

Of course further, if someOptionalIntExpression is really an expression, it might need to be extracted to a local, for the compiler to know that the expression can’t mutate.

Is there a Kotlin idiom that helps? Also, I similarly would like to do:
if (someOptionalInt1 + someOptionalInt2 > 0), which is an extension of the first issue.


#2

someOptionalIntExpression?.let { it > 0} ?: false.

If you can treat null as 0 (or any other value), you could write (someOptionalIntExpression ?: 0) > 0 and (someOptionalInt1 ?: 0) + (someOptionalInt2 ?: 0) > 0.


#3

you can have an extension for Int? as such:

fun Int?.orZero() = this ?: 0

#4

thanks ahmadalsharif.dev worked 3d perfectly.