Skip to content
DeveloperMemos

isEmpty vs isBlank in Kotlin

Kotlin, Android Development1 min read

When working with strings in Kotlin, you often need to check if a string is empty or contains only whitespace characters. In such cases, Kotlin provides two commonly used methods: isEmpty and isBlank. Although they may seem similar, there are significant differences in their behavior. This article aims to clarify the distinctions between these methods and provide examples of when to use each one.

The Difference between isEmpty and isBlank

isEmpty

The isEmpty method is used to determine whether a string is empty, meaning it has a length of zero. It returns true if the string is empty, and false otherwise. Let's consider an example:

1val emptyString = ""
2val nonEmptyString = "Hello, World!"
3
4println(emptyString.isEmpty()) // Output: true
5println(nonEmptyString.isEmpty()) // Output: false

As shown in the example above, calling isEmpty on an empty string returns true, while calling it on a non-empty string returns false.

isBlank

On the other hand, the isBlank method determines whether a string is considered blank, which means it either contains no characters or consists only of whitespace characters (e.g., spaces, tabs, line breaks). It returns true if the string is blank, and false otherwise. Here's an example:

1val blankString = " "
2val nonBlankString = "Hello, World!"
3
4println(blankString.isBlank()) // Output: true
5println(nonBlankString.isBlank()) // Output: false

In the above example, calling isBlank on a string consisting of only spaces returns true, while calling it on a non-blank string returns false.

Use Cases

Now that we understand the difference between isEmpty and isBlank, let's explore some common use cases for each method.

isEmpty Use Cases

  • Form Validation: When validating user input, you may want to check if a required input field is empty before proceeding.
  • Checking Collection Size: You can use isEmpty to determine if a collection (e.g., list, set) is empty before performing operations on it.

isBlank Use Cases

  • Removing Whitespace: Before processing a user's input, you might want to trim leading and trailing whitespace using isBlank to ensure the input doesn't contain any unintended whitespace characters.
  • Ignoring Empty Lines: To process a file or text input, you may need to filter out empty lines using isBlank to exclude them from further processing.

Wrapping Up

In Kotlin, knowing when to use isEmpty and isBlank is important for effectively handling strings in different scenarios. While isEmpty checks for an empty string by length, isBlank also considers strings that consist solely of whitespace characters as blank. Understanding the differences between these methods will help you write cleaner and more reliable code in your Android development projects.