0
0
KotlinHow-ToBeginner · 3 min read

How to Check if String is Blank in Kotlin

In Kotlin, you can check if a string is blank by using the isBlank() function. This function returns true if the string is empty or contains only whitespace characters.
📐

Syntax

The isBlank() function is called on a string variable or literal. It returns a Boolean value:

  • true if the string is empty or has only whitespace (spaces, tabs, newlines).
  • false if the string contains any non-whitespace characters.
kotlin
val text: String = "  "
val result: Boolean = text.isBlank()
💻

Example

This example shows how to use isBlank() to check different strings and print whether they are blank or not.

kotlin
fun main() {
    val emptyString = ""
    val spacesString = "   "
    val textString = "Hello"

    println(emptyString.isBlank())   // true
    println(spacesString.isBlank())  // true
    println(textString.isBlank())    // false
}
Output
true true false
⚠️

Common Pitfalls

A common mistake is confusing isBlank() with isEmpty(). isEmpty() returns true only if the string has zero characters, but isBlank() also returns true for strings with only spaces or tabs.

Example of wrong and right usage:

kotlin
fun main() {
    val spaces = "   "

    // Wrong: using isEmpty() to check blank strings
    println(spaces.isEmpty())  // false

    // Right: use isBlank() to check if string is empty or whitespace
    println(spaces.isBlank())  // true
}
Output
false true
📊

Quick Reference

FunctionDescriptionReturns true for
isBlank()Checks if string is empty or only whitespaceEmpty string, spaces, tabs, newlines
isEmpty()Checks if string has zero charactersEmpty string only

Key Takeaways

Use isBlank() to check if a string is empty or contains only whitespace.
isBlank() returns true for strings with spaces, tabs, or newlines.
isEmpty() only returns true for completely empty strings.
Always choose isBlank() when you want to treat whitespace-only strings as blank.