Use == instead of ?: when dealing with nullable boolean

Why you should care

Nullable boolean can be null, or having a value “true” or “false”.

var a: Boolean?  // a is a nullable boolean

Before accessing the value, we should verify if the variable is null or not. This can be done with the classical check : if … else … For exemple, to check against true:

if ((a != null) && (a == true)) { ... } else { ... }

In Kotlin it is possible to use a compact syntax using the elvis operator. (a ?: b) is equivalent to (if (a !=null) a else b). So checking a nullable Boolean to true can be shortly done with the elvis operator like that:

if ( a ?: false ) { ... } else { .... }

Unfortunately, even this is shortest it is nevertheless worse and indigest for many persons because of the boolean inversion. So, prefer using the direct check to the value, without checking the nullity:

if ( a == true ) { ... } else { .... }

How we detect

CAST Highlight counts one occurrence each time the pattern ?:true or ?:false is encountered.



About CAST and Highlight’s Code Insights

Over the last 25 years, CAST has leveraged unique knowledge on software quality measurement by analyzing thousands of applications and billions of lines of code. Based on this experience and community standards on programming best practices, Highlight implements hundreds of code insights across 15+ technologies to calculate health factors of a software.