BRDroid
BRDroid

Reputation: 4408

kotlin - how to minimise the if statement with null checks

I doing a small calculation and I have a if clause where I am checking if any of the value is null then donot perform the operations

Is there an easy way to write this in Kotlin without so many null checks in a if statement

   if (pfTotal != null && departureTotal != null && upTotal != null && density != null) {
                    customArDisc =
                        (pflTotal - (departureTotal - upTotal)) / density * THOUSAND
                    customArDiscPercentage =
                        customArDisc / (pfTotal / density * THOUSAND) * PERCENTAGE
                }

Thanks in advance R

Upvotes: 0

Views: 43

Answers (1)

cactustictacs
cactustictacs

Reputation: 19622

It's not a lot shorter (not for four things anyway), but you could do something like

val dependencies = listOf(pfTotal, departureTotal, upTotal, density)
if (dependencies.all { it != null }) {
    // do stuff
}

or for nulls specifically

if (!dependencies.contains(null))

and you could write a nicely named extension function/property that's clearer about what you're doing and what it's used for.

Bear in mind, if those are vars and not vals then there's no guarantee they're still non-null once you try to use them!


Another approach you could use is some kind of state object/data class that holds non-null versions of each property. And to create it, you call a builder function with all those values, it does the null checking, and returns the complete object, or null if one of the values was null.

That way, you either have the valid state object to do your calculations with, or you don't. This is just pushing the null check into a different place, but it might be helpful if you're doing a bunch of things with one set of data, and you just want to validate it once


Or you could just YOLO it and wrap your function in a try/catch that looks for NullPointerExceptions. Wouldn't recommend it though!

Upvotes: 1

Related Questions