andThen

inline fun <I, O> KotlinResult<I>.andThen(success: (I) -> O): KotlinResult<O>

Transforms the encapsulated value if this instance represents success, wrapping the success lambda in result so that any thrown exception is re-encapsulated as a failure rather than propagating.

Unlike Result.map, exceptions from success are caught. Unlike Result.mapCatching, CancellationException is also caught — do not use in suspend contexts.

Failures pass through unchanged.

result { 4 }
.andThen { it * 2 } // Result.success(8)
.andThen { check(false) { it } } // Result.failure(IllegalStateException("8"))
.andThen { 16 } // Remains Result.failure(IllegalStateException("8"))

Parameters

I

The encapsulated success input type.

O

The output type after transformation.

See also