kotlinkotlin-coroutineshigher-order-functions

Coroutine Higher Order Function Glitch?


Higher order function can take function as parameter and/or return them as result.

Given the higher order function:

fun highOrder(func:()->Unit ){
    println("this is a higher order function")
    func()
}

There are two ways to use it:

fun main() {
    highOrder( ::doSomething )
    highOrder { doSomething() }
}

Given:

suspend fun getFromServer(): String {
    println("Working Hard!")
    delay(4_000)
    return "Server Response"
}

why am i unable to execute coroutine in same manner?

this is possible:

CoroutineScope(Dispatchers.IO).launch (block = { getFromServer() })

this is NOT:

CoroutineScope(Dispatchers.IO).launch (block = ::getFromServer )

Error msg: "inferred type is KSuspendFunction0 but suspend CoroutineScope.() -> Unit was expected"

While I understand this is not the recommended approach for launching coroutines, I'm curious why the latter implementation isn't working. How can I make it work?

the block parameter is looking for

suspend CoroutineScope.() -> Unit

is it possible to define a function that obeys that?

i have had striped and renamed the the function to:

suspend fun CoroutineScope.getFromServer() {
    println("Working Hard!")
    delay(4_000) 
}

and it still did not work.


Solution

  • You're almost there. Now that getFromServer() has CoroutineScope as its receiver, calling it as a function reference looks like this: CoroutineScope::getFromServer

    So this will work:

    CoroutineScope(Dispatchers.IO).launch(block = CoroutineScope::getFromServer)
    

    You could still return String instead of Unit if you want, the return value would just be ignored.