In this tutorial, you shall learn how to check if given string is empty in Kotlin, using String.isEmpty() function, with examples.

Kotlin – Check if String is Empty

To check if string is empty in Kotlin, call isEmpty() method on this string. The method returns a boolean value of true, if the string is empty, or false if the string is not empty.

Syntax

The syntax of isEmpty() method is

fun CharSequence.isEmpty(): Boolean

Since isEmpty() returns a boolean value, we can use this as a condition in Kotlin If-Else statement.

ADVERTISEMENT

Examples

In the following example, we take a string in str and check if this string is empty or not using isEmpty().

Main.kt

fun main(args: Array<String>) {
    var str = ""
    if (str.isEmpty()) {
        println("The string is empty.")
    } else {
        println("The string is not empty.")
    }
}

Output

The string is empty.

Now, let us take a non-empty string in str, and find the output.

Main.kt

fun main(args: Array<String>) {
    var str = "hello world"
    if (str.isEmpty()) {
        println("The string is empty.")
    } else {
        println("The string is not empty.")
    }
}

Output

The string is not empty.

Conclusion

In this Kotlin Tutorial, we learned how to check if given string is empty or not using String.isEmpty(), with examples.