Kotlin String - isEmpty() Function



The Kotlin string isEmpty() function is used to check whether the string has a character sequence. If the string is empty returns true.

This function is commonly used in scenarios where we want to validate input, handle optional data, or avoid operations on empty strings.

Syntax

Following is the syntax of the Kotlin string isEmpty() function −

fun CharSequence.isEmpty(): Boolean

Parameters

This function does not accepts any parameters.

Return value

This function returns a Boolean value, which is true if the string is empty; Otherwise false.

Example 1: Check If a String Empty or Not

Following is the basic example, here how we can use isEmpty() with a string in kotlin −

fun main() {
   // empty string
   val string = ""
   val res = string.isEmpty()
   if(res == true){
      println("string is empty")
   }
   else {
      println("string is not empty")
   }
}

Output

Following is the output −

string is empty

Example 2: Input Validation

Now, let's see another example. For input validation, we are using the isEmpty() function to check if a user has provided input in a form field before proceeding −

fun main() {
   val userInput = "Aman123"
   if (userInput.isEmpty()) {
      println("Please enter a valid input.")
   } else {
      println("Thank you for your input.")
   }
}

Output

If input field is filled −

Thank you for your input.

Example 3: If the String is non-empty

In this example, theisEmpty()function returns false if we use this function with a non-empty string −

fun main() {
   val userInput = "Aman123"
   val res = userInput.isEmpty()
   println("is string empty?: ${res}")
}

Output

Following is the output −

is string empty?: false
kotlin_strings.htm
Advertisements