简体   繁体   中英

Kotlin: Higher-order function with Suspend Function return type

How to return suspend function from regular function? How to create suspend function instance?

For example, I can return async result from function:

fun <T> f(g: () -> T): Deferred<T> = GlobalScope.async { g() }

But I notices Kotlin allow the following signature of function:

fun <T> f(g: () -> T): suspend () -> T {
    TODO()
}

How can I implement it?

@Rene 的回答但更短:

fun <T> f(g: () -> T) = suspend { g() }

One way to do it:

fun <T> f(g: () -> T): suspend () -> T {
    suspend fun intern() = g()
    return ::intern
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM