File tree 2 files changed +11
-6
lines changed
kotlinx-coroutines-core/common
2 files changed +11
-6
lines changed Original file line number Diff line number Diff line change @@ -63,7 +63,6 @@ public suspend fun <T> Flow<T>.single(): T {
63
63
}
64
64
65
65
if (result == = NULL ) throw NoSuchElementException (" Expected at least one element" )
66
- @Suppress(" UNCHECKED_CAST" )
67
66
return result as T
68
67
}
69
68
@@ -72,12 +71,12 @@ public suspend fun <T> Flow<T>.single(): T {
72
71
* Throws [IllegalStateException] for flow that contains more than one element.
73
72
*/
74
73
public suspend fun <T > Flow<T>.singleOrNull (): T ? {
75
- var result: T ? = null
74
+ var result: Any ? = NULL
76
75
collect { value ->
77
- if (result != null ) error(" Expected only one element" )
76
+ if (result != NULL ) error(" Expected only one element" )
78
77
result = value
79
78
}
80
- return result
79
+ return if ( result == = NULL ) null else result as T ?
81
80
}
82
81
83
82
/* *
Original file line number Diff line number Diff line change @@ -25,8 +25,14 @@ class SingleTest : TestBase() {
25
25
emit(239L )
26
26
emit(240L )
27
27
}
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() }
30
36
}
31
37
32
38
@Test
You can’t perform that action at this time.
0 commit comments