|
|
|
|
|
by ptx
1776 days ago
|
|
They are similar but slightly different. "single" checks that there is exactly one matching element: >>> listOf(1, 2, 3).single { it > 2 }
res0: kotlin.Int = 3
>>> listOf(1, 2, 3).single { it > 1 }
java.lang.IllegalArgumentException: Collection contains more than one matching element.
>>> listOf(1, 2, 3).single { it > 100 }
java.util.NoSuchElementException: Collection contains no element matching the predicate.
Whereas "firstOrNull" returns the first result even if there are more, or null if there are none: >>> listOf(1, 2, 3).firstOrNull { it > 2 }
res0: kotlin.Int? = 3
>>> listOf(1, 2, 3).firstOrNull { it > 1 }
res1: kotlin.Int? = 2
>>> listOf(1, 2, 3).firstOrNull { it > 100 }
res2: kotlin.Int? = null
Python's "next" function kind of acts like "single", except that it doesn't check that there aren't more than one matching element. I wish the itertools module had a function that did this. |
|