Return true when Bigdecimal variable is different from null, otherwise return false

Asked

Viewed 103 times

1

  • I have a type attribute BigDecimal x.

  • I need to call a method exampleMethod().

  • I would like to pass the parameter true or false depending on whether x is null or not, as in the example below:

    val x: BigDecimal? = null 
    
    if (x != null)
        exampleMethod(true)
    else
        exampleMethod(false)
    

There is another more optimized way to verify that it is null and returns true or false so I don’t need to use the if? As in the Java example below:

exampleMethod(Objects.nonNull(x))
  • Did the answer resolve what was in doubt? Do you need something else to be improved? Do you think it is possible to accept it now?

1 answer

2

Guaranteed more optimized has no, but shorter has:

exampleMethod(x != null)

An expression that has a relational operator always results in a boolean value, so true whether that comparison is true and false if it is not, and these values are exactly what you want to use as argument in the call of the method, then there is no reason to turn around, use directly the value that the expression results.

The Java way should work also if you import the package correctly, but I find it quite unnecessary because internally it will make the comparison I indicated. I change my mind if someone shows me why this abstraction brings some advantage. It just doesn’t work if using Kotlin outside the JVM or similar (has on Android also), as commented below, and this would be one more reason not to use something dependent on it.

  • 1

    To complete the Maniero answers, if you are running Kotlin in the JVM you can use the Java API without problems. Your own example of code is valid in Kotlin: exampleMethod(Objects.nonNull(x)). Depending on the situation there are also idiomatic options like the Elvis Operator; for more information take a look at the official documentation on Null Safety.

  • Thank you both. the/

  • 1

    Maniero, off-topic, but responding to his update. In that case there is no advantage to using Objects.nonNull same. This method was introduced in Java 8 and can be used as an idiomatic alternative to Amble when a predicate is expected. E.g., stream.filter(Objects::nonNull) as an alternative to stream.filter(elem -> elem != null)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.