Is it possible to create a non-suspendable functio...
# getting-started
j
Is it possible to create a non-suspendable function with an overloaded suspendable version? I was thinking about something like that:
Copy code
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
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
I did try to inline it but it seems like its not possible with a suspendable lambda as a parameter?
s
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
I see, thank you, I will create 2 functions then 😛