From 614bd19ad5298bdf1504b8c2d190b1d6cad4e34d Mon Sep 17 00:00:00 2001 From: pacien Date: Fri, 5 Apr 2019 04:25:09 +0200 Subject: add shortcuts for mapping adapters --- .../java/org/pacien/lemonad/attempt/Attempt.java | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) (limited to 'src/main/java/org/pacien/lemonad') diff --git a/src/main/java/org/pacien/lemonad/attempt/Attempt.java b/src/main/java/org/pacien/lemonad/attempt/Attempt.java index dcbb2d3..d5d82ed 100644 --- a/src/main/java/org/pacien/lemonad/attempt/Attempt.java +++ b/src/main/java/org/pacien/lemonad/attempt/Attempt.java @@ -80,6 +80,16 @@ public interface Attempt { return (Attempt) (isSuccess() ? mapper.apply(getResult()) : this); } + /** + * @param mapper a function producing an {@link Attempt}, called with the current result if this {@link Attempt} is a success. + * @param errorAdapter a function adapting any intermediate error returned by the {@code mapper} function. + * @return this {@link Attempt} if it is a failure, or the produced one otherwise. + */ + default Attempt mapResult(@NonNull Function> mapper, + @NonNull Function errorAdapter) { + return mapResult(result -> mapper.apply(result).mapError(error -> failure(errorAdapter.apply(error)))); + } + /** * @param mapper a function producing an {@link Attempt}, called with the current error if this {@link Attempt} is a failure. * @return this {@link Attempt} if it is a success, or the alternative {@link Attempt} retrieved from the supplier otherwise. @@ -89,6 +99,16 @@ public interface Attempt { return (Attempt) (isFailure() ? mapper.apply(getError()) : this); } + /** + * @param mapper a function producing an {@link Attempt}, called with the current error if this {@link Attempt} is a failure. + * @param resultAdapter a function adapting any intermediate result returned by the {@code mapper} function. + * @return this {@link Attempt} if it is a success, or the alternative {@link Attempt} retrieved from the supplier otherwise. + */ + default Attempt mapError(@NonNull Function> mapper, + @NonNull Function resultAdapter) { + return mapError(error -> mapper.apply(error).mapResult(result -> success(resultAdapter.apply(result)))); + } + /** * @param resultMapper a function producing an {@link Attempt}, called with the current result if this {@link Attempt} is a success. * @param errorMapper a function producing an {@link Attempt}, called with the current error if this {@link Attempt} is a failure. -- cgit v1.2.3