resultOf

inline suspend fun <T> resultOf(finally: () -> Unit = ::unit, block: () -> T): KotlinResult<T>

Suspend runner that catches and encapsulates T and most thrown Exceptions as a KotlinResult.

  • Will NOT catch CancellationException if the coroutine is no longer active.

  • Does NOT catch Error subtypes. Errors are always fatal.

Prefer this over result in suspend contexts.

val a: KotlinResult<String> = resultOf { throw Exception() } // Result.failure(Exception())
val b: KotlinResult<String> = resultOf { "Hello, World!" } // Result.success("Hello, World!")

Return

The KotlinResult of block.

Parameters

T

The return type of block.

finally

An optional cleanup block, always runs after block.

block

The protected block to execute. May throw an exception.

See also

Throws

Always propagated — errors are fatal.

CancellationException

If the coroutine has been cancelled.