Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Check Double value is Null or Zero in kotlin

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

like image 256
user3309336 Avatar asked Mar 02 '19 06:03

user3309336


1 Answers

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:

  1. When 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.
  2. When 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.
  3. When 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.
like image 183
Sam Avatar answered Sep 19 '22 00:09

Sam