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

Although I like the answer by @miensol very much, my answer would be (and that is why I do not put it in a comment): if (s != null && s.isNotEmpty()) { … } actually is the idiomatic way in Kotlin. Only this way will you get a smart cast to String inside the block, while with the way in the accepted answer you will have to use s!! inside the block.


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
}