How to idiomatically check non-empty, non-empty strings in Kotlin?

I'm new to Kotlin, and I'm looking for tips that rewrite the following code in a more elegant way.

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.

+5
source share
3 answers

You can use isNullOrEmpty or its friend isNullOrBlank like this:

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

Both isNullOrEmpty and isNullOrBlank are extension methods on CharSequence? , so you can safely use them with null . Alternatively, turn null to false as follows:

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

Although I really like @miensol's answer, my answer will be (and that’s why I don’t put it in the comments): if (s != null && s.isNotEmpty()) { … } is actually an idiomatic way in Kotlin. Only in this way you will get a smart tide in String inside the block, and with the accepted answer you will have to use s!! inside the block.

+2
source

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") } 
0
source

Source: https://habr.com/ru/post/1261325/


All Articles