Introduce firstNotNullOf and firstNotNullOfOrNull #KT-12109
This commit is contained in:
@@ -436,6 +436,22 @@ class MapTest {
|
||||
doTest("built Map", builtMap, "y", 24)
|
||||
}
|
||||
|
||||
@Test
|
||||
fun firstNotNullOf() {
|
||||
val map = mapOf("Alice" to 20, "Tom" to 13, "Bob" to 18)
|
||||
|
||||
val firstAdult = map.firstNotNullOf { (name, age) -> name.takeIf { age >= 18 } }
|
||||
val firstAdultOrNull = map.firstNotNullOfOrNull { (name, age) -> name.takeIf { age >= 18 } }
|
||||
|
||||
assertEquals("Alice", firstAdult)
|
||||
assertEquals("Alice", firstAdultOrNull)
|
||||
|
||||
assertFailsWith<NoSuchElementException> { val firstChild = map.firstNotNullOf { (name, age) -> name.takeIf { age <= 11 } } }
|
||||
val firstChildOrNull = map.firstNotNullOfOrNull { (name, age) -> name.takeIf { age <= 11 } }
|
||||
|
||||
assertNull(firstChildOrNull)
|
||||
}
|
||||
|
||||
|
||||
fun testPlusAssign(doPlusAssign: (MutableMap<String, Int>) -> Unit) {
|
||||
val map = hashMapOf("a" to 1, "b" to 2)
|
||||
|
||||
@@ -731,6 +731,20 @@ public class SequenceTest {
|
||||
assertEquals(s2, s2.orEmpty())
|
||||
}
|
||||
|
||||
@Test
|
||||
fun firstNotNullOf() {
|
||||
fun Int.isMonodigit(): Boolean = toString().toHashSet().size == 1
|
||||
fun Int.doubleIfNotMonodigit(): Int? = if (this > 9 && this.isMonodigit()) this * 2 else null
|
||||
|
||||
assertEquals(110, fibonacci().firstNotNullOf { it.doubleIfNotMonodigit() })
|
||||
assertEquals(110, fibonacci().firstNotNullOfOrNull { it.doubleIfNotMonodigit() })
|
||||
|
||||
assertFailsWith<NoSuchElementException> {
|
||||
fibonacci().take(10).firstNotNullOf<Int, Int> { it.doubleIfNotMonodigit() }
|
||||
}
|
||||
assertNull(fibonacci().take(10).firstNotNullOfOrNull { it.doubleIfNotMonodigit() })
|
||||
}
|
||||
|
||||
/*
|
||||
test fun pairIterator() {
|
||||
val pairStr = (fibonacci() zip fibonacci().map { i -> i*2 }).joinToString(limit = 10)
|
||||
|
||||
Reference in New Issue
Block a user