How to use the orEmpty() method of string in Kotlin

Overview

The orEmpty() method returns an empty string if the value of the invoking input variable is null. Otherwise, it returns the input string’s value.

Syntax

fun String?.orEmpty(): String

Argument: This method doesn’t take any argument.

Return value

This method returns the invoking input string value if the input string is not equal to null. Otherwise, it returns an empty string.

Code

The code below demonstrates the use of the orEmpty() method:

fun main() {
var str = null;
println("str : ${str}.");
println("str.orEmpty() : ${str.orEmpty()}.");
var notNullStr = "test";
println("\nnotNullStr : ${notNullStr}.");
println("notNullStr.orEmpty() : ${notNullStr.orEmpty()}.");
}

Code explanation

Line 2: We created a new variable named str and assign null as the value.

Line 4: We call the orEmpty method on the str. The orEmpty method checks if the str’s value is null. In our case, the value is null, so an empty string is returned.

Line 6: We create a new variable named notNullStr and assign the String - test— as the value.

Line 8: We call the orEmpty method on the notNullStr. The orEmpty method checks if the input string’s value is null. In our case, the value is test and not null. Therefore, test is returned.

Free Resources