https://kotlinlang.org logo
#coroutines
Title
# coroutines
a

ansman

09/04/2020, 5:14 PM
Hmm, why is
Flow.firstOrNull
restricted to non nullable types? Feels like it'd be useful even with flows with nullable types?
c

Casey Brooks

09/04/2020, 5:16 PM
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

ansman

09/04/2020, 5:19 PM
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

louiscad

09/04/2020, 5:57 PM
Almost no one wraps values in optionals in Kotlin. You can use
transformWhile
for your use case.
a

ansman

09/04/2020, 5:58 PM
For what use case? Getting the first element or null?
l

louiscad

09/04/2020, 5:58 PM
firstOrNull for nullable types.
a

ansman

09/04/2020, 5:59 PM
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

louiscad

09/04/2020, 6:03 PM
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

ansman

09/04/2020, 6:04 PM
Implementing this operator is trivial and that isn't what I'm asking for here
l

louiscad

09/04/2020, 6:06 PM
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

ansman

09/04/2020, 6:06 PM
9 Views