Kotlin List single()
Syntax & Examples
Syntax of List.single()
There are 2 variations for the syntax of List.single() extension function. They are:
1.
fun <T> List<T>.single(): T
This extension function returns the single element, or throws an exception if the list is empty or has more than one element.
2.
fun <T> Iterable<T>.single(predicate: (T) -> Boolean): T
This extension function returns the single element matching the given predicate, or throws exception if there is no or more than one matching element.
✐ Examples
1 Example
In this example,
- We create a list of integers named
list
containing the element42
. - We use the
single()
function to get the single element from the list. - The result, which is
42
, is stored inresult
. - We print
result
usingprintln()
.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf(42)
val result = list.single()
println(result)
}
Output
42
2 Example
In this example,
- We create a list of characters named
list
containing elements'a', 'b', 'c'
. - We use the
single
function with a predicate that checks if an element is equal to'b'
. - The result, which is
'b'
, is stored inresult
. - We print
result
usingprintln()
.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf('a', 'b', 'c')
val result = list.single { it == 'b' }
println(result)
}
Output
b
3 Example
In this example,
- We create a list of strings named
list
containing the element"apple"
. - We use the
single
function with a predicate that checks if the length of the element is greater than5
. - Since there is no element in the list that satisfies the predicate, calling
single()
with this predicate throws an exception.
Kotlin Program
fun main(args: Array<String>) {
val list = listOf("apple")
val result = list.single { it.length > 5 }
println(result)
}
Output
Exception in thread "main" java.util.NoSuchElementException: Collection contains no element matching the predicate.
Summary
In this Kotlin tutorial, we learned about single() extension function of List: the syntax and few working examples with output and detailed explanation for each example.