Kotlin String orEmpty()

Kotlin String orEmpty() Tutorial

The String?.orEmpty() extension function in Kotlin is used to handle nullable strings. It returns the original string if it is not null, or an empty string (“”) if the original string is null. This function is useful for safely working with nullable strings without encountering null pointer exceptions.

In this tutorial, we’ll explore the syntax of the orEmpty() function and provide examples of its usage in Kotlin strings.

Syntax

The syntax of the orEmpty() function is as follows:

fun String?.orEmpty(): String

The String?.orEmpty() function is an extension function for nullable strings. It can be called on a nullable string and returns a non-null string, either the original string or an empty string if the original string is null.

Examples for String?.orEmpty() function

1. Handle Nullable String in Kotlin using String.orEmpty()

In this example, we’ll use orEmpty() to handle a nullable string, ensuring that we always have a non-null string for further processing.

  1. Take a nullable string value in nullableString.
  2. Call orEmpty() on nullableString. The function returns the original string if it is not null, or an empty string if it is null.
  3. You may use the resulting non-null string for further processing or print it to the console output.

Kotlin Program

fun main() {
    val nullableString: String? = "Hello World"

    // Using orEmpty() to handle a nullable string
    val resultString = nullableString.orEmpty()

    // Printing the original nullable string and the resulting non-null string
    println("Original Nullable String:\n$nullableString\n")
    println("Resulting Non-null String:\n$resultString")
}

Output

Original Nullable String:
Hello World

Resulting Non-null String:
Hello World

2. Handle Null String using String.orEmpty()

In this example, we’ll use orEmpty() to handle a null string, ensuring that we get an empty string for further processing.

  1. Take a nullable string value in nullString.
  2. Call orEmpty() on nullString. The function returns an empty string since the original string is null.
  3. You may use the resulting empty string for further processing or print it to the console output.

Kotlin Program

fun main() {
    val nullString: String? = null

    // Using orEmpty() to handle a null string
    val resultString = nullString.orEmpty()

    // Printing the original null string and the resulting empty string
    println("Original Null String:\n$nullString\n")
    println("Resulting Empty String:\n$resultString")
}

Output

Original Null String:
null

Resulting Empty String:

Summary

In this tutorial, we’ve covered the orEmpty() extension function in Kotlin strings, its syntax, and how to use it to handle nullable strings by returning the original string if it’s not null or an empty string if it is null. This function is a convenient way to ensure non-null values for further processing.