Checking if string is empty in Kotlin

Use isEmpty when you want to test that a String is exactly equal to the empty string "".

Use isBlank when you want to test that a String is empty or only consists of whitespace ("", " ").

Avoid using == "".


For String? (nullable String) datatype, I use .isNullOrBlank()

For String, I use .isBlank()

Why? Because most of the time, I do not want to allow Strings with whitespace (and .isBlank() checks whitespace as well as empty String). If you don't care about whitespace, use .isNullorEmpty() and .isEmpty() for String? and String, respectively.


Don't use myString == "", in java this would be myString.equals("") which also isn't recommended.

isBlank is not the same as isEmpty and it really depends on your use-case.

isBlank checks that a char sequence has a 0 length or that all indices are white space. isEmpty only checks that the char sequence length is 0.

/**
 * Returns `true` if this string is empty or consists solely of whitespace characters.
 */
public fun CharSequence.isBlank(): Boolean = length == 0 || indices.all { this[it].isWhitespace() }


/**
 * Returns `true` if this char sequence is empty (contains no characters).
 */
@kotlin.internal.InlineOnly
public inline fun CharSequence.isEmpty(): Boolean = length == 0

Tags:

Kotlin