Check if a string is empty or null in Kotlin
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.
|
1 2 3 4 5 |
fun main() { val str = "" val isNullOrEmpty = str.isNullOrEmpty() println(isNullOrEmpty) // true } |
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.
|
1 2 3 4 |
fun main() { val str = "" println(str == null || str.isEmpty()) // true } |
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 ?::
|
1 2 3 4 5 |
fun main() { val str: String? = "" val isNullOrEmpty = str?.isEmpty() ?: true println(isNullOrEmpty) // true } |
To check for the opposite, i.e., the string is not empty, use the isNotEmpty() function.
|
1 2 3 4 5 |
fun main() { val str: String? = "" val isNotNullOrEmpty = str?.isNotEmpty() ?: false println(isNotNullOrEmpty) // false } |
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:
|
1 2 3 4 |
fun main() { val str = "" println(str == null || str.length == 0) // true } |
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 "".
|
1 2 3 4 |
fun main() { val str = "" println(str == null || str == "") // true } |
5. Using isNullOrBlank() function
You can use the isNullOrBlank() function to additionally check for whitespace characters along with null or empty.
|
1 2 3 4 5 |
fun main() { val str = " " val isNullOrBlank = str.isNullOrBlank() println(isNullOrBlank) // true } |
That’s all about determining whether a string is empty or null in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)