Kotlin List singleOrNull()
Syntax & Examples
Syntax of List.singleOrNull()
There are 2 variations for the syntax of List.singleOrNull() extension function. They are:
1.
fun <T> List<T>.singleOrNull(): T?This extension function returns single element, or null if the list is empty or has more than one element.
2.
fun <T> Iterable<T>.singleOrNull( predicate: (T) -> Boolean ): T?This extension function returns the single element matching the given predicate, or null if element was not found or more than one element was found.
✐ Examples
1 Example
In this example,
- We create a list named
listcontaining an integer[8]. - We call the
singleOrNull()function onlistto get the single element, if exists, ornullif the list is empty or has more than one element. - Since the list has only one element, the resulting value is
8, and is stored insingleElement. - Finally, we print the
singleElementto standard output using theprintlnfunction.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf(8);
val singleElement = list.singleOrNull();
println(singleElement);
}Output
8
2 Example
In this example,
- We create a list named
listcontaining the characters['a', 'b', 'c']. - We call the
singleOrNullfunction with a predicate onlistto get the single element matching the given predicate, ornullif no such element is found or more than one element is found. - The predicate checks if the element is equal to
'b'. - The result, which is the single element
'b'ornull, is stored insingleElement. - Finally, we print the
singleElementto standard output using theprintlnfunction.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf('a', 'b', 'c');
val singleElement = list.singleOrNull { it == 'b' };
println(singleElement);
}Output
b
Summary
In this Kotlin tutorial, we learned about singleOrNull() extension function of List: the syntax and few working examples with output and detailed explanation for each example.