3 ms·
I thought it was first or firstOrNull. Or is there a new Kotlin collection method I need to learn about? Aside, Kotlin collection extensions might be my favori
by manyxcxi 5y ago
I thought it was first or firstOrNull. Or is there a new Kotlin collection method I need to learn about?
Aside, Kotlin collection extensions might be my favorite thing I learned in the last two years.
- ptx 5y agoThey 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.