How to Check if String is Empty in Kotlin
In Kotlin, you can check if a string is empty using the
isEmpty() function or by comparing it to an empty string "". For example, myString.isEmpty() returns true if the string has no characters.Syntax
The main way to check if a string is empty in Kotlin is by using the isEmpty() function. It returns true if the string has zero characters.
You can also compare the string directly to an empty string "" using ==.
kotlin
val myString = "" val isEmpty = myString.isEmpty() // true val isEmptyCompare = (myString == "") // true
Example
This example shows how to check if a string is empty using isEmpty() and prints a message accordingly.
kotlin
fun main() {
val emptyString = ""
val nonEmptyString = "Hello"
if (emptyString.isEmpty()) {
println("The string is empty.")
} else {
println("The string is not empty.")
}
if (nonEmptyString.isEmpty()) {
println("The string is empty.")
} else {
println("The string is not empty.")
}
}Output
The string is empty.
The string is not empty.
Common Pitfalls
A common mistake is to check if a string is empty by comparing it to null instead of checking if it has zero characters. Remember, isEmpty() only checks for empty strings, not null.
To safely check for both null and empty strings, use isNullOrEmpty().
kotlin
fun main() {
val nullableString: String? = null
// Wrong: This will cause an error if string is null
// println(nullableString.isEmpty())
// Right: Use isNullOrEmpty to check for null or empty
if (nullableString.isNullOrEmpty()) {
println("String is null or empty.")
} else {
println("String has content.")
}
}Output
String is null or empty.
Quick Reference
| Method | Description | Returns |
|---|---|---|
| isEmpty() | Checks if string has zero characters | Boolean (true if empty) |
| == "" | Compares string to empty string | Boolean (true if empty) |
| isNullOrEmpty() | Checks if string is null or empty | Boolean (true if null or empty) |
Key Takeaways
Use
isEmpty() to check if a string has no characters.Comparing a string to
"" also works to check emptiness.Use
isNullOrEmpty() to safely check for null or empty strings.Avoid calling
isEmpty() on nullable strings without a null check.Empty string means zero characters, different from null which means no value.