Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

516
Views
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

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!