https://kotlinlang.org logo
#getting-started
Title
# getting-started
m

Mark

09/25/2020, 4:46 AM
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

spand

09/25/2020, 4:49 AM
Cant you ask intellij to convert it ?
m

Mark

09/25/2020, 4:49 AM
It doesn’t come up with any such recommendation. So perhaps not possible
n

nanodeath

09/25/2020, 4:51 AM
does
?.let(FlowCollector::emit)
not work?
🚫 1
s

spand

09/25/2020, 4:51 AM
Ah, I think there are limits to method references and suspend functions
m

Mark

09/25/2020, 4:55 AM
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

spand

09/25/2020, 5:04 AM
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

Mark

09/25/2020, 5:05 AM
Yes, I agree that’s much better. Just figuring out why some things don’t work :)
s

spand

09/25/2020, 5:14 AM
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

Mark

09/25/2020, 6:07 AM
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

spand

09/25/2020, 6:13 AM
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

Mark

09/25/2020, 6:39 AM
Isn’t
this::emit
synonymous with
::emit
?
s

spand

09/25/2020, 6:47 AM
Yes. I meant vs
FlowCollector::emit
Lets just stop here. Its just turning into me rambling
😀 1
4 Views