How to check if a string is empty in Kotlin?


In this article, we will see three different ways to check whether a String is empty in Kotlin.

Example – isEmpty()

Kotlin library function isEmpty() can be used in order to check whether a String is empty. Note that it counts spaces too.

fun main(args: Array<String>) {

   // No space between the quotes
   val myString = ""

   // Space between the quotes
   val anotherString = " "

   println(myString.isEmpty())

   // this will return false as we have a space
   println(anotherString.isEmpty())
}

Output

On execution, it will produce the following output −

true
false

Observe that the second string is not empty because it contains a space.

Example – isBlank()

isBlank() can be used to check whether a String value is blank or not. We will be getting True for both the scenario used above, as the value actually contains a blank value.

fun main(args: Array<String>) {

   // Without Space
   val myString = ""

   // With Space
   val anotherString = " "

   // Both the strings are blank
   println(myString.isBlank())
   println(anotherString.isBlank())
}

Output

On execution, it will produce the following output −

true
true

Example – isNullOrBlank() or isNullOrEmpty()

isNullOrBlank() and isNullOrEmpty() are the other two functions that can be used to check whether a given string is empty or not.

fun main(args: Array<String>) {

   // string without space
   val myString = ""

   // string with a space
   val anotherString = " "

   //true :: null and blank
   println(myString.isNullOrBlank()?.toString())

   //true ::null and empty
   println(myString.isNullOrEmpty()?.toString())

   //true :: null and blank
   println(anotherString.isNullOrBlank()?.toString())

   //false :: null but not empty; contains whiteSpace
   println(anotherString.isNullOrEmpty()?.toString())
}

Output

It will generate the following output −

true
true
true
false

Updated on: 01-Mar-2022

4K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements