Is it possible to add null check in if

For example:

if (null) → false

if (not_null_obj) → true

this can save some time on checking a variable is null like:

if (object == null)
if (object != null)

I am not sure whether it’s a good language design, just a thought in my mind :slight_smile:

2 Likes

if is currently restricted to Boolean, not even Boolean?. Expanding it to Any? is dangerous, particularly for the previously safe Booleans. If you use it for nullability, false isn’t null, so it should be accepted, but that doesn’t make any sense.

I agree with @derektom14, I’d rather keep if construct explicit, to ease readability. However, I’m a long damned Java dev, so maybe I’m a lost cause on this :slight_smile:

However, There’s already an explicit way to do such thing. It requires a few extra-characters though. Not sure if it is really better than a plain old if(value != null):

fun nullIfElse(value : Any?) {
     value?.run {
         println("Go here if $value is presentl")
     } ?: run {
         println("Go here if null")
     }
 }
 
 nullIfElse(null)
 nullIfElse("anything")

The one thing I don’t like about the nullIfElse setup is that using run will change the context of this and using let will introduce an it that is the same as value, which can get weird. Of course, if you’re doing container.value?.let { value -> ... }, this can be a major boon, but if it’s already an immutable value I prefer using if (value != null) { ... }

I’m against implicit conversion to bool, but would greatly approve some unary operator for null checks.
Like postfix ?? or prefix !!:

if (value?.nullableField??) {
  println(value.nullableField)
}

Even for booleans, there’s the question of whether null should be treated as true, or as false. In my experience, both cases appear about equally often, so an operator which only worked one way would be frustrating and likely to cause bugs.

Better IMHO to use some of the existing, more explicit options:

if (someNullableBoolean ?: true) // Treats null as true

if (someNullableBoolean ?: false) // Treats null as false

if (someNullableBoolean == true) // Treats null as false

if (someNullableBoolean != false) // Treats null as true

None of those are long or complicated, and none involve language changes.

2 Likes

There has been a discussion about the idom for nullable boolean checks here.
Also the official guidelines say that you should prefer using someNullableBoolean == true or someNulullableBoolean == false over the elvis operator.
https://kotlinlang.org/docs/reference/idioms.html#consuming-a-nullable-boolean

Thanks all above for the very detailed explanation, yes as a C++ developer as well, I kindof like some of the C++ ways like if for null check, and I do realize that in a strong type language like Kotlin, explicit Boolean for if check is very helpful and safe. :grinning: