Skip to content

Commit 1de6bf0

Browse files
committed
Allow nullable types in Flow's firstOrNull extension
This closes Kotlin#2229
1 parent ae6b2c4 commit 1de6bf0

File tree

2 files changed

+9
-3
lines changed

2 files changed

+9
-3
lines changed

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

+3-3
Original file line numberDiff line numberDiff line change
@@ -124,7 +124,7 @@ public suspend fun <T> Flow<T>.first(predicate: suspend (T) -> Boolean): T {
124124
* The terminal operator that returns the first element emitted by the flow and then cancels flow's collection.
125125
* Returns `null` if the flow was empty.
126126
*/
127-
public suspend fun <T : Any> Flow<T>.firstOrNull(): T? {
127+
public suspend fun <T> Flow<T>.firstOrNull(): T? {
128128
var result: T? = null
129129
try {
130130
collect { value ->
@@ -138,10 +138,10 @@ public suspend fun <T : Any> Flow<T>.firstOrNull(): T? {
138138
}
139139

140140
/**
141-
* The terminal operator that returns the first element emitted by the flow matching the given [predicate] and then cancels flow's collection.
141+
* The terminal operator that returns the first element emitted by the flow matching the given [predicate] and then cancels flow's collection.
142142
* Returns `null` if the flow did not contain an element matching the [predicate].
143143
*/
144-
public suspend fun <T : Any> Flow<T>.firstOrNull(predicate: suspend (T) -> Boolean): T? {
144+
public suspend fun <T> Flow<T>.firstOrNull(predicate: suspend (T) -> Boolean): T? {
145145
var result: T? = null
146146
try {
147147
collect { value ->

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

+6
Original file line numberDiff line numberDiff line change
@@ -127,6 +127,12 @@ class FirstTest : TestBase() {
127127
assertNull(emptyFlow<Int>().firstOrNull { true })
128128
}
129129

130+
@Test
131+
fun testFirstOrNullWithNullElement() = runTest {
132+
assertNull(flowOf<String?>(null).firstOrNull())
133+
assertNull(flowOf<String?>(null).firstOrNull { true })
134+
}
135+
130136
@Test
131137
fun testFirstOrNullWhenErrorCancelsUpstream() = runTest {
132138
val latch = Channel<Unit>()

0 commit comments

Comments
 (0)