Any reason the suspend keyword is not supported with anonymous functions?

I like anonymous functions, they have different semantics than lambdas while still being easily assignable to a variable for callbacks etc.
But any reason they do not work with the keyword suspend?


I can confirm that anonymous functions can’t be suspended. The following expression failed:

        example.runLambda((fun(): String = "world") as suspend () -> String)

Here is an example on how to declare use of suspendible lambda, implementation of suspendible lambda and use of suspendible lambda:

package example

import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
import kotlin.coroutines.EmptyCoroutineContext

interface Example {
    // Declare method that takes a suspendable lambda lambda
    fun runLambda(hello: suspend () -> String)

class ExampleImpl : Example {
    private val scope = CoroutineScope(EmptyCoroutineContext)

    // Implement the method
    override fun runLambda(hello: suspend () -> String) {
        scope.launch { println("Hello, ${hello()}!") }

fun main(args: Array<String>) {
    val example = ExampleImpl()
    // Then use the lambda
    example.runLambda {

absolutely amazing reply brother, I am just a bit confused by the design choice to allow ordinal functions and lambda functions to be suspended but not anonymous functions in particular.


Hard to know why

1 Like