2

So, I'm fairly new to coroutines in kotlin and I don't understand what's going on here. I do have a suspended function called from another one.

What's the right syntax here?

suspend fun doSomething(str: Optional<String>) {
  // Error: Suspension functions can be called only within coroutine body
  str.map { doSomethingElse() } 
}

suspend fun doSomethingElse() { }

whereas, this is fine

suspend fun doSomething(str: Optional<String>) {
  if (str.isPresent) {
    doSomethingElse()
  }
}

suspend fun doSomethingElse() {}
  • Does this answer your question? [Suspend function 'callGetApi' should be called only from a coroutine or another suspend function](https://stackoverflow.com/questions/53928668/suspend-function-callgetapi-should-be-called-only-from-a-coroutine-or-another) – Sergio Jul 29 '20 at 05:55
  • @Sergey I think OP understands what that question is about. The confusion here is about why you seemingly can't call a suspend function from inside another suspend here. It's because the lambda isn't `inline`. – Tenfour04 Jul 29 '20 at 15:01

1 Answers1

1

Optional.map() is not an inline function. The passed lambda is an interface, so if you try to call a suspend function from the interface, you are no longer calling it from a coroutine.

In this case, you can convert the Optional<String> to a nullable String? with .orElse(null) and then call the function if the result is non-null. Optional is Java's solution for null-safety because Java doesn't support it at the syntax/compiler level. You don't need to use it in Kotlin code, unless it is passed to you from Java code.

Tenfour04
  • 83,111
  • 11
  • 94
  • 154