tryRecover

inline fun <T> KotlinResult<T>.tryRecover(failure: (Throwable) -> T): KotlinResult<T>

Attempts to recover from a failure by transforming the encapsulated Throwable into a success value, wrapping failure in result.

Unlike Result.recover, exceptions from failure are caught and re-encapsulated. Unlike Result.recoverCatching, CancellationException is also caught — do not use in suspend contexts.

Successes pass through unchanged.

result { 4 }                                    // Result.success(4)
.tryRecover { Unit } // No change — Result.success(4)
.andThen { throw FileNotFoundException("test") } // Result.failure(FileNotFoundException("test"))
.tryRecover { 7 } // Result.success(7)

See also