Return the Result in on{Success,Failure}

This facilitates chaining onSuccess/onFailure calls that may perform
arbitrary side-effects, such as logging.
This commit is contained in:
Michael Bull 2018-11-01 11:25:20 +00:00
parent 4eb5d80f91
commit 3a3b5415a7
1 changed files with 16 additions and 4 deletions

View File

@ -1,11 +1,23 @@
package com.github.michaelbull.result package com.github.michaelbull.result
/** /**
* Invokes a [callback] if this [Result] is [Ok]. * Invokes an [action] if this [Result] is [Ok].
*/ */
inline infix fun <V, E> Result<V, E>.onSuccess(callback: (V) -> Unit) = mapBoth(callback, {}) inline infix fun <V, E> Result<V, E>.onSuccess(action: (V) -> Unit): Result<V, E> {
if (this is Ok) {
action(value)
}
return this
}
/** /**
* Invokes a [callback] if this [Result] is [Err]. * Invokes an [action] if this [Result] is [Err].
*/ */
inline infix fun <V, E> Result<V, E>.onFailure(callback: (E) -> Unit) = mapBoth({}, callback) inline infix fun <V, E> Result<V, E>.onFailure(action: (E) -> Unit): Result<V, E> {
if (this is Err) {
action(error)
}
return this
}