isNotEmpty() method returns null on Nullable string object


#1

Hi

Till now I was using isNotEmpty as below

       val a : String? = null
       if(a?.isNotEmpty()!!){
                  <do something>
       }

As I knew that as per isNotEmpty() method’s definition it will either return true or false but can not return null if a is null. But today i faced NPE with this method.
Below is isNotEmpty() method’s definition

      @kotlin.internal.InlineOnly
      public inline fun CharSequence.isNotEmpty(): Boolean = length > 0

please help me to understand if this is Bug or feature or i am missing something here.

Due to this now I am using above code as below

       val a : String? = null
       if(a?.isNotEmpty() == true){
                  <do something>
       }

I am currently using Android Studio 3.1.2 on Ubuntu 16.04 and Kotlin version is 1.2.41


#2

I guess you understand that a?.isNotEmpty can return either null if a is null or the result of a.isNotEmpty(). If not you should take another look at the documentation under Safe Calls.
So when you use !! it will throw a NPE if a is null.

If itself can not handle nullable parameters (I’m not sure where this is explained exactly, I think it is somewhere in the documentation but I can not find it right now). That’s why you have to use the comparison.

null == true => false
false == true => false
true == true => true

You could also create your own utility


fun String?.isNotNullNorEmpty() =
	this?.isNotEmpty() == true
// or
fun String?.isNotNullNorEmpty() =
	this?.isNotEmpty() ?: false

Btw, once you understand safe calls properly I would prefer my second utility as it is easier to understand IMO, considering how safe calls work. But I guess that is preference and not universally right.


#3

@Wasabi375 Thanks for quick reply. How can I miss this silly point that if string is null then isNotEmpty() will not be executed at all. Also thanks for utility methods, I will implement these. :slight_smile:


#4

Kotlin already has isNullOrEmpty on String? so no need to write a function yourself.


#5

Woops wasn’t thinking about this function :wink: I was in explanation mode and not thinking about the best solution but more about how to explain the mistake @silwar made.
But yeah using isNullOrEmpty and inverting it is definitely a better solution.


#6

You did a great job explaining this Kotlin behaviour, so I’m sure others will benefit from the explanation.

But yes, we want the easiest solution too :wink: All part of being a community. We watch over each other…