https://kotlinlang.org logo
Title
j

Johann Pardanaud

05/11/2023, 3:07 PM
Is it possible to create a non-suspendable function with an overloaded suspendable version? I was thinking about something like that:
fun runBlock(block: () -> Unit) = block()
suspend fun runBlock(block: suspend () -> Unit) = block()

runBlock { println("hello") }
^ COMPILE ERROR: Suspend function 'runBlock' should be called only from a coroutine or another suspend function

runBlock(suspend { println("hello") })
^ COMPILE ERROR: Suspend function 'runBlock' should be called only from a coroutine or another suspend function
Or should I create two functions,
runBlock
and
runSuspendableBlock
? (sorry, I post quite often lately 😓 )
s

Sam

05/11/2023, 3:14 PM
If
runBlock
was
inline
it would work. But in the general case, no, a
suspend
function can’t overload or override a non-suspending function 😞
j

Johann Pardanaud

05/11/2023, 3:15 PM
I did try to inline it but it seems like its not possible with a suspendable lambda as a parameter?
s

Sam

05/11/2023, 3:19 PM
Yeah, the inline trick only works if you actually call it with an inlined lambda
By calling
suspend { println("hello") }
you are actually creating an instance; it’s no longer inline
At least, I think that’s the reason. It might actually still end up being inlined but either way the type system doesn’t like it.
j

Johann Pardanaud

05/11/2023, 3:40 PM
I see, thank you, I will create 2 functions then 😛