Reputation: 10604
Currently, I have the following in my code
fun use(consumer: (T) -> Unit) {
consumer(this.value)
}
suspend fun useS(consumer: suspend (T) -> Unit) {
consumer(this.value)
}
These are 2 methods that are actually doing the same. However, I was not able to merge them into one, nor to use overloaded method. In some places my consumer argument is a regular function, on other places it is suspend
function; I do not have control over that.
Is it possible to have just one method, regardless of my consumer "suspendability"?
EDIT: forgot to mention that this.value
is private
and hence using inline
would not work - still, I am in control of that, so might change the visibility of the value
field.
Upvotes: 0
Views: 52
Reputation: 25573
IF the code really is as simple as you've provided, simply using the non-suspend version and make it inline
would solve your issues.
By making it inline (and thus inlining the consumer) it allows the inner block to use the calling environment of the caller. This is why all the library helper functions like also
can be used in a suspend function and call suspend functions without explicitly being suspend functions themselves.
Upvotes: 2