1. Overview

Depending on our nullability constraints and other requirements, there are a few extensions in Kotlin that can help us to determine the emptiness of a String.

In this short tutorial, we’re going to get familiar with those functions to check if a String is empty or even blank in Kotlin.

2. Empty Strings

String is empty if its length is zero. In order to determine if a non-nullable String is empty or not, we can use the isEmpty() extension function:

val empty = ""
assertTrue { empty.isEmpty() }

On the other hand, to check if a String is not empty, in addition to the negation operator, we can also use the isNotEmpty() extension function:

val nonEmpty = "42"
assertTrue { nonEmpty.isNotEmpty() }

In addition to Strings, these extensions are applicable to all sorts of CharSequences such as StringBuilder:

val sb = StringBuilder()
assertTrue { sb.isEmpty() }

Here, we’re making sure the given StringBuilder is actually empty.

For nullable Strings, it’s also possible to check if the value is either null or empty using the isNullOrEmpty() function:

val nullStr: String? = null
val emptyNullable: String? = ""

assertTrue { nullStr.isNullOrEmpty() }
assertTrue { emptyNullable.isNullOrEmpty() }

2.1. Simplifying Conditional Logic

Sometimes we may need traditional if-else conditional branches to work around empty values:

val ipAddress = request.getHeader("X-FORWARDED-FOR")
val source = if (ipAddress.isEmpty()) "default-value" else ipAddress

As of Kotlin 1.3, we can avoid this imperative style with a more functional approach using the ifEmpty()higher-order function:

val source = request.getHeader("X-FORWARDED-FOR").ifEmpty { "default-value" }

As we see, this is much simpler and more concise!

3. Blank Strings

String is blank when either its length is zero or it contains only whitespace characters. In order to check if a non-nullable String is blank, we can use the isBlank() function:

val blank = "    "
val empty = ""
val notBlank = "  42"

assertTrue { empty.isBlank() }
assertTrue { blank.isBlank() }
assertTrue { notBlank.isNotBlank() }

Similar to isNotEmpty(), the isNotBlank() function serves as a more readable alternative for the negation operator.

Again, quite similar to isNullOrEmpty(), there’s an isNullOrBlank() function:

val nullStr: String? = null
val blankNullable: String? = "   "

assertTrue { nullStr.isNullOrBlank() }
assertTrue { blankNullable.isNullOrBlank() }

This function returns true if the value is either null or blank. In addition to all these similarities, the ifBlank() higher-order function helps us to provide defaults for blank values.

4. Conclusion

In this tutorial, we got familiar with a few functions that can help us to check if a string is empty or blank.

As usual, all the examples are available over on GitHub.

Comments are closed on this article!