2

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
piotrek1543
  • 19,130
  • 7
  • 81
  • 94
Zouyiu Ng
  • 193
  • 1
  • 12

1 Answers1

2

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() }
}
ChristianB
  • 2,452
  • 2
  • 10
  • 22