kotlinkotlin-null-safety

How to idiomatically test for non-null, non-empty strings in Kotlin?


I am new to Kotlin, and I am looking for help in rewriting the following code to be more elegant.

var s: String? = "abc"
if (s != null && s.isNotEmpty()) {
    // Do something
}

If I use the following code:

if (s?.isNotEmpty()) {

The compiler will complain that

Required: Boolean
Found: Boolean?

Thanks.


Solution

  • You can use isNullOrEmpty or its friend isNullOrBlank like so:

    if(!s.isNullOrEmpty()){
        // s is not empty
    }
    

    Both isNullOrEmpty and isNullOrBlank are extension methods on CharSequence? thus you can use them safely with null. Alternatively turn null into false like so:

    if(s?.isNotEmpty() ?: false){
        // s is not empty
    }
    

    you can also do the following

    if(s?.isNotEmpty() == true){ 
        // s is not empty
    }