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.
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.
The Kotlin isEmpty checks whether the string is empty whereas isBlank checks whether the string is empty or contains white space characters.
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.
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
}
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.
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.
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")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With