From 3a3b5415a748ad75bc133097e9d7b7cfd0d73cb8 Mon Sep 17 00:00:00 2001 From: Michael Bull Date: Thu, 1 Nov 2018 11:25:20 +0000 Subject: [PATCH] Return the Result in on{Success,Failure} This facilitates chaining onSuccess/onFailure calls that may perform arbitrary side-effects, such as logging. --- .../com/github/michaelbull/result/On.kt | 20 +++++++++++++++---- 1 file changed, 16 insertions(+), 4 deletions(-) diff --git a/src/main/kotlin/com/github/michaelbull/result/On.kt b/src/main/kotlin/com/github/michaelbull/result/On.kt index 6826a0f..dd44c1e 100644 --- a/src/main/kotlin/com/github/michaelbull/result/On.kt +++ b/src/main/kotlin/com/github/michaelbull/result/On.kt @@ -1,11 +1,23 @@ package com.github.michaelbull.result /** - * Invokes a [callback] if this [Result] is [Ok]. + * Invokes an [action] if this [Result] is [Ok]. */ -inline infix fun Result.onSuccess(callback: (V) -> Unit) = mapBoth(callback, {}) +inline infix fun Result.onSuccess(action: (V) -> Unit): Result { + 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 Result.onFailure(callback: (E) -> Unit) = mapBoth({}, callback) +inline infix fun Result.onFailure(action: (E) -> Unit): Result { + if (this is Err) { + action(error) + } + + return this +}