Why Kotlin can't reference to suspend function as the parameter of let/also and other functions?
class X
fun a(x: X) {}
suspend fun b(x: X) {}
X().let(::a)
X().let(::b) // Error: Type mismatch
Why Kotlin can't reference to suspend function as the parameter of let/also and other functions?
class X
fun a(x: X) {}
suspend fun b(x: X) {}
X().let(::a)
X().let(::b) // Error: Type mismatch
You can only call suspend
functions from a coroutine or another suspend function.
And let
does not take a suspend function as a parameter.
public inline fun <T, R> T.let(block: (T) -> R): R
So as with any other type, the function declaration has to match. Passing a suspend function to another function that does not accept a suspend function will not work.
It would work when you have a function like:
This is just an example, no real usecase for a suspend function for printing a log!
suspend inline fun log(block: suspend () -> String) {
val message: String = block() // we assume block takes some time to be computed
return println(message) // once its available, we print it
}
You can use the log
function like:
suspend fun complexError(): String {
// takes time to compute...
return "message"
}
// usage
suspend fun errorHandling() {
log(::complexError) // pass a reference to complexError()
// or
log() { complexError() }
}