Hmm, why is `Flow.firstOrNull` restricted to non n...
# coroutines
a
Hmm, why is
Flow.firstOrNull
restricted to non nullable types? Feels like it'd be useful even with flows with nullable types?
c
If it were used on a nullable flow, when that method returns you have no way of knowing if it was because the Flow emitted a null value, or if the flow closed without emitting anything. In the first case,
null
is a valid value, while in the second case,
null
is a signal of an error
a
Right, but that's up to the caller to decide if they want that or not
If you need that for nullable types just wrap it in an optional or something like that.
l
Almost no one wraps values in optionals in Kotlin. You can use
transformWhile
for your use case.
a
For what use case? Getting the first element or null?
l
firstOrNull for nullable types.
a
I still don't understand what you mean by that
The list version of
firstOrNull()
does not have this restriction and neither should
Flow
IMO
Just to be clear, I'm not asking how to implement this operator or an alternative. I'm asking specifically why
firstOrNull
does not allow nullable types when the list and array version does
l
My two sentences were two distinct statements. Here's a snippet to illustrate my second statement:
Copy code
fun <E> Flow<E>.firstOrNullForNullables() = transformWhile {
    emit(it)
    false
}
a
Implementing this operator is trivial and that isn't what I'm asking for here
l
You make a point with the
List
version. Might make sense to submit the API change request in GitHub issues then. Good news is that is should be binary compatible if it's accepted.
a