Difference between isNullOrEmpty and isNullOrBlank in Kotlin

Kotlin Mobile DevelopmentApps/Applications

Both these functions, isNullOrEmpty and isNullOrBlank, are used in Kotlin whenever it is required to check if a String value is empty or not. Let's check how these two functions are different from each other.

  • isNullOrBlank – It takes whitespaces into account, which means " " is different from "". This function will return True only when the String is declared with no characters in it. It will check whether the value of the String is NULL and it will also check whether the String is blank.

  • isNullOrEmpty() – This function checks whether the string is declared as NULL or whether it is empty. Whenever String.length returns "0", then this function will return True, otherwise False.

Example – isNullOrBlank vs. isNullOrEmpty

The following example demonstrates the difference between isNullorBlank and isNullOrEmpty

fun main(args: Array<String>) {
   val String1 = " "
   val String2 = ""

   // String1 is Null but not empty
   // String1 contains whitespace
   println(String1.isNullOrEmpty())

   // Null and empty: True
   // isNullOrBlank counts whitespace as blank
   println(String1.isNullOrBlank())

   // String2 has no whitespaces
   println(String2.isNullOrEmpty())
   println(String2.isNullOrBlank())
}

Output

It will produce the following output −

false
true
true
true
raja
Updated on 16-Mar-2022 12:09:22

Advertisements