Kotlin List orEmpty()
Syntax & Examples
Syntax of List.orEmpty()
The syntax of List.orEmpty() extension function is:
fun <T> List<T>?.orEmpty(): List<T>This orEmpty() extension function of List returns this List if it's not null and the empty list otherwise.
✐ Examples
1 Example
In this example,
- We declare a nullable list named
listand assign it a value ofnull. - We apply the
orEmpty()function to the list, which returns an empty list because the original list is null. - Finally, we print the resulting empty list to standard output using the
printlnfunction.
Kotlin Program
fun main(args: Array<String>) {
val list: List<String>? = null;
val result = list.orEmpty();
println(result);
}Output
[]
2 Example
In this example,
- We create a list named
listcontaining the characters['a', 'b', 'c', 'd', 'e']. - We apply the
orEmpty()function to the list, which returns the original list because it's not null. - Finally, we print the original list to standard output using the
printlnfunction.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf('a', 'b', 'c', 'd', 'e');
val result = list.orEmpty();
println(result);
}Output
[a, b, c, d, e]
3 Example
In this example,
- We create a list named
listcontaining the strings['apple', 'banana', 'orange', 'grape']. - We apply the
orEmpty()function to the list, which returns the original list because it's not null. - Finally, we print the original list to standard output using the
printlnfunction.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("apple", "banana", "orange", "grape");
val result = list.orEmpty();
println(result);
}Output
[apple, banana, orange, grape]
Summary
In this Kotlin tutorial, we learned about orEmpty() extension function of List: the syntax and few working examples with output and detailed explanation for each example.