Skip to content

Commit 7d006bb

Browse files
committed
Properly handle multiple nulls
1 parent e8c44f1 commit 7d006bb

File tree

2 files changed

+11
-6
lines changed

2 files changed

+11
-6
lines changed

kotlinx-coroutines-core/common/src/flow/terminal/Reduce.kt

+3-4
Original file line numberDiff line numberDiff line change
@@ -63,7 +63,6 @@ public suspend fun <T> Flow<T>.single(): T {
6363
}
6464

6565
if (result === NULL) throw NoSuchElementException("Expected at least one element")
66-
@Suppress("UNCHECKED_CAST")
6766
return result as T
6867
}
6968

@@ -72,12 +71,12 @@ public suspend fun <T> Flow<T>.single(): T {
7271
* Throws [IllegalStateException] for flow that contains more than one element.
7372
*/
7473
public suspend fun <T> Flow<T>.singleOrNull(): T? {
75-
var result: T? = null
74+
var result: Any? = NULL
7675
collect { value ->
77-
if (result != null) error("Expected only one element")
76+
if (result != NULL) error("Expected only one element")
7877
result = value
7978
}
80-
return result
79+
return if (result === NULL) null else result as T?
8180
}
8281

8382
/**

kotlinx-coroutines-core/common/test/flow/terminal/SingleTest.kt

+8-2
Original file line numberDiff line numberDiff line change
@@ -25,8 +25,14 @@ class SingleTest : TestBase() {
2525
emit(239L)
2626
emit(240L)
2727
}
28-
assertFailsWith<RuntimeException> { flow.single() }
29-
assertFailsWith<RuntimeException> { flow.singleOrNull() }
28+
assertFailsWith<IllegalStateException> { flow.single() }
29+
assertFailsWith<IllegalStateException> { flow.singleOrNull() }
30+
}
31+
32+
@Test
33+
fun testMultipleNulls() = runTest {
34+
val flow = flowOf<Int?>(null, null)
35+
assertFailsWith<IllegalStateException> { flow.singleOrNull() }
3036
}
3137

3238
@Test

0 commit comments

Comments
 (0)