When declaring a `suspend fun` can we declare that...
# multiplatform
t
When declaring a
suspend fun
can we declare that it will never throw? I want to get rid of the
try await
and instead just have
await
. Is this possible?
Copy code
data class Thing(val item: Int)

class ThingRepository {
    suspend fun getThing(succeed: Boolean): Thing {
        delay(100.milliseconds)
        return Thing(0)
    }
}
Copy code
Task {
    let thing = await ThingRepository().getThingSimple(succeed: true)
    print("Thing is \(thing).")
}
To give some insight. I wish to return a Either/Result type instead and thus the error will never be present
m
I think
CancellationException
is always added to the list of exceptions that can be thrown. I don't think there is any way to prevent that. All the other exceptions are fatal unless you mark the function as throwing. The decision to convert that doesn't fully make sense. I assume the scope that is being used to launch the actual suspending function cannot be canceled, and the API doesn't expose a way to cancel the job. That only leaves Rogue Cancellation exceptions (https://betterprogramming.pub/the-silent-killer-thats-crashing-your-coroutines-9171d1e8f79b), which I think should be treated like any other exception. But I'm not really sure how the suspend function calling from Objective-C works.
j
On the JVM, that code is susceptible to OOM, StackOverflowError, VerifyError, NoClassDefFoundError, and probably more thanks to delay living in a separate library. I'm not sure exactly how native works here, but I would think at the very least there's out of memory and stack overflow equivalents that are still possible
m
Unless you declare the the function as throwing those runtime exceptions, they will not be thrown in Swift and instead are always fatal exceptions. From the documentation generated in the header file.
Copy code
* @note This method converts instances of CancellationException to errors.
 * Other uncaught Kotlin exceptions are fatal.