Checking if string is empty in Kotlin

Viewed 42009

In Java, we've always been reminded to use myString.isEmpty() to check whether a String is empty. In Kotlin however, I find that you can use either myString == "" or myString.isEmpty() or even myString.isBlank().

Are there any guidelines/recommendations on this? Or is it simply "anything that rocks your boat"?

Thanks in advance for feeding my curiosity. :D

5 Answers

There are two methods available in Kotlin.

  1. isNullOrBlank()
  2. isNullOrEmpty()

And the difference is:

data = " " // this is a text with blank space 
 
println(data.isNullOrBlank()?.toString())  //true
println(data.isNullOrEmpty()?.toString())  //false

You can use isNullOrBlank() to check is a string is null or empty. This method considers spaces only strings to be empty.

Here is a usage example:

val s: String? = null
println(s.isNullOrBlank())
val s1: String? = ""
println(s1.isNullOrBlank())
val s2: String? = "     "
println(s2.isNullOrBlank())
val s3: String? = "  a "
println(s3.isNullOrBlank())

The output of this snippet is:

true
true
true
false
Related