This article explores different ways to check if a string is empty or null in Kotlin.

1. Using isNullOrEmpty() function

The standard approach in Kotlin to check for a null or an empty string is with the isNullOrEmpty() function.

Download Code

2. Using isEmpty() function

Alternatively, you can use the isEmpty() function to check for an empty string in Kotlin. To check for null as well, it should be preceded by a null check.

Download Code

 
Instead of explicitly checking if the string is null, you can use the safe call operator, written as ?. along with the Elvis operator, written as ?::

Download Code

 
To check for the opposite, i.e., the string is not empty, use the isNotEmpty() function.

Download Code

3. Using length property

The isEmpty() function internally checks the length property of a string. A String is empty if its length is 0. You can directly call the length property, as shown below:

Download Code

4. Using == operator

Another solution is to perform an equality check against an empty string. Consider the following code, which tests that a string is exactly equal to the empty string "".

Download Code

5. Using isNullOrBlank() function

You can use the isNullOrBlank() function to additionally check for whitespace characters along with null or empty.

Download Code

That’s all about determining whether a string is empty or null in Kotlin.