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

iForests picture iForests · Dec 15, 2016 · Viewed 13.2k times · Source

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.

Answer

miensol picture miensol · Dec 15, 2016

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
}