Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 754
iForests Avatar asked Dec 15 '16 11:12

iForests


People also ask

Is not empty Kotlin string?

To check if string is empty in Kotlin, call isEmpty() method on this string. The method returns a boolean value of true, if the string is empty, or false if the string is not empty.

Is not blank VS is not empty Kotlin?

The Kotlin isEmpty checks whether the string is empty whereas isBlank checks whether the string is empty or contains white space characters.

What is non-null assertion in Kotlin?

The not null assertion (!!) operator converts any value to a non-null type and throws an exception if the value is null. If anyone want NullPointerException then he can ask explicitly using this operator.


4 Answers

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
}
like image 85
miensol Avatar answered Oct 20 '22 09:10

miensol


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.

like image 5
Michael Piefel Avatar answered Oct 20 '22 08:10

Michael Piefel


Or you can create an Extension Function:

public inline fun String?.ifNotEmpty(crossinline block: (String) -> Unit): Unit {
    if (this != null && this.isNotEmpty()) {
        block(this)
    }
}

See it in action

I find this approach more readable in context of Jetpack Compose which is a UI Toolkit.

handles.twitter.ifNotEmpty {
    SocialMediaItem(handle = it, type = SocialMedia.TWITTER)
}

In this case the intention is to only display that block of UI if Twitter handle is not null, and is not an empty string.

like image 2
Nevercom Avatar answered Oct 20 '22 08:10

Nevercom


or create an extension method and use it as a safe call:

fun String?.emptyToNull(): String? {
    return if (this == null || this.isEmpty()) null else this
}

fun main(args: Array<String>) {
    val str1:String?=""
    val str2:String?=null
    val str3:String?="not empty & not null"

    println(str1.emptyToNull()?:"empty string")
    println(str2.emptyToNull()?:"null string")
    println(str3.emptyToNull()?:"will not print")
}
like image 1
mt.uulu Avatar answered Oct 20 '22 08:10

mt.uulu