Is there any way to write this using a function re...
# getting-started
m
Is there any way to write this using a function reference (e.g.
::emit
)?
Copy code
suspend fun FlowCollector<Something>.emitNotNull(something: Something?) {
    something?.let { emit(it) }
}
s
Cant you ask intellij to convert it ?
m
It doesn’t come up with any such recommendation. So perhaps not possible
n
does
?.let(FlowCollector::emit)
not work?
🚫 1
s
Ah, I think there are limits to method references and suspend functions
m
I suppose anyway should be using
also
but then get similar:
Copy code
Type mismatch.
Required:
(TypeVariable(T)) → Unit
Found:
KSuspendFunction1<Something, Unit>
This works:
Copy code
suspend fun FlowCollector<Something>.emitNotNull(something: Something?) {
    something?.suspendingAlso(::emit)
}

suspend inline fun <T> T.suspendingAlso(block: suspend (T) -> Unit): T {
    block(this)
    return this
}
s
Your
::emit
is
this::emit
. I am not sure this is what you want? ie. creating a bound reference on every call. In any case I think this is much more readable (but maybe your example is contrived):
Copy code
suspend fun FlowCollector<String>.emitNotNull(something: String?) {
        if (something != null) emit(something)
    }
m
Yes, I agree that’s much better. Just figuring out why some things don’t work :)
s
I think what threw me off at first was that
FlowCollector::emit
is actually a two parameter function. One for the receiver and one for the value to emit. This doesnt work nicely with let and method reference. The reason it works as a lambda is that receiver is passed implicitly.
m
I don’t think that’s the issue.
::emit
would work if emit was not suspending?
Copy code
fun FlowCollector<Something>.notSuspending(something: Something?) {
    
}

suspend fun FlowCollector<Something>.emitNotNull(something: Something?) {
    something?.also(::emit) // does not compile
    something?.also(::notSuspending) // does compile
}
s
Right. There is the suspending part also. Mostly I am just talking about this because I see
this::emit
as a work-around to my issue (and not generally desirable).
m
Isn’t
this::emit
synonymous with
::emit
?
s
Yes. I meant vs
FlowCollector::emit
Lets just stop here. Its just turning into me rambling
😀 1