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 list containing an integer [8].
  • We call the singleOrNull() function on list to get the single element, if exists, or null if 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 in singleElement.
  • Finally, we print the singleElement to standard output using the println function.

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 list containing the characters ['a', 'b', 'c'].
  • We call the singleOrNull function with a predicate on list to get the single element matching the given predicate, or null if 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' or null, is stored in singleElement.
  • Finally, we print the singleElement to standard output using the println function.

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.