Skip to content

Commit

Permalink
Get rid of NULL comparison because of T: Any upper bound in firstOrNull
Browse files Browse the repository at this point in the history
  • Loading branch information
qwwdfsad committed Mar 16, 2020
1 parent 8694e97 commit 4aefef4
Showing 1 changed file with 4 additions and 5 deletions.
9 changes: 4 additions & 5 deletions kotlinx-coroutines-core/common/src/flow/terminal/Reduce.kt
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,6 @@ public suspend fun <T: Any> Flow<T>.singleOrNull(): T? {
if (result != null) error("Expected only one element")
result = value
}

return result
}

Expand Down Expand Up @@ -126,7 +125,7 @@ public suspend fun <T> Flow<T>.first(predicate: suspend (T) -> Boolean): T {
* Returns `null` if the flow was empty.
*/
public suspend fun <T : Any> Flow<T>.firstOrNull(): T? {
var result: Any? = NULL
var result: Any? = null
try {
collect { value ->
result = value
Expand All @@ -135,15 +134,15 @@ public suspend fun <T : Any> Flow<T>.firstOrNull(): T? {
} catch (e: AbortFlowException) {
// Do nothing
}
return result.takeUnless { it === NULL } as T?
return result.takeUnless { it === null } as T?
}

/**
* The terminal operator that returns the first element emitted by the flow matching the given [predicate] and then cancels flow's collection.
* Returns `null` if the flow did not contain an element matching the [predicate].
*/
public suspend fun <T : Any> Flow<T>.firstOrNull(predicate: suspend (T) -> Boolean): T? {
var result: Any? = NULL
var result: Any? = null
try {
collect { value ->
if (predicate(value)) {
Expand All @@ -154,5 +153,5 @@ public suspend fun <T : Any> Flow<T>.firstOrNull(predicate: suspend (T) -> Boole
} catch (e: AbortFlowException) {
// Do nothing
}
return result.takeUnless { it === NULL } as T?
return result.takeUnless { it === null } as T?
}

0 comments on commit 4aefef4

Please sign in to comment.