How to Check Double value is Null or Zero in kotlin
val ratio:Double? = 0.0
val calRatio = if (ratio == null || ratio == 0.0)
0.12
else
ratio
ratio in null , 0.0 , 0.1
if ratio null or 0.0 then return 0.12
and ratio is 0.2 or more then return same ratio value
how to check this algorithm not use if statement
You can write this in idomatic Kotlin without an if
statement using takeUnless
.
val ratio: Double? = 0.0
val calRatio = ratio.takeUnless { it == 0.0 } ?: 0.12
The takeUnless
call checks whether the number matches the predicate it == 0.0
. If the predicate evaluates to true
, null
is returned. Only when the predicate evaluates to false
is the actual number returned.
We can see why this works by considering the three possible cases:
ratio
is null
, the predicate it == 0.0
evaluates to false
. The call to ratio.takeUnless { it == 0.0 }
returns the value of ratio
, which is null
. Because its left-hand-side operand is null
, the ?:
operator returns the right-hand-side value of 0.12
.ratio
is 0.0
, the predicate it == 0.0
evaluates to true
. The call to ratio.takeUnless { it == 0.0 }
ignores the value of ratio
and instead returns null
. Because its left-hand-side operand is null
, the ?:
operator returns the right-hand-side value of 0.12
.ratio
is any non-null, non-zero number, the predicate it == 0.0
evaluates to false
. The call to ratio.takeUnless { it == 0.0 }
returns the value of ratio
, which is the original number. Because its left-hand-side operand is not null, the ?:
operator returns the left-hand-side value.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