From 0ac555a6d383fa76626a6123e008365e005558a3 Mon Sep 17 00:00:00 2001 From: pacien Date: Fri, 5 Apr 2019 03:00:45 +0200 Subject: add missing map method --- src/main/java/org/pacien/lemonad/attempt/Attempt.java | 11 +++++++++++ src/test/java/org/pacien/lemonad/attempt/AttemptTest.java | 15 ++++++++++----- 2 files changed, 21 insertions(+), 5 deletions(-) diff --git a/src/main/java/org/pacien/lemonad/attempt/Attempt.java b/src/main/java/org/pacien/lemonad/attempt/Attempt.java index e36ac4b..9f5befa 100644 --- a/src/main/java/org/pacien/lemonad/attempt/Attempt.java +++ b/src/main/java/org/pacien/lemonad/attempt/Attempt.java @@ -89,6 +89,17 @@ public interface Attempt { return (Attempt) (isFailure() ? mapper.apply(getError()) : this); } + /** + * @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. + * @return the transformed {@link Attempt}. + */ + default Attempt map(@NonNull Function> resultMapper, + @NonNull Function> errorMapper) { + //noinspection unchecked + return (Attempt) (isSuccess() ? resultMapper.apply(getResult()) : errorMapper.apply(getError())); + } + /** * @param mapper a function transforming an {@link Attempt}. * @return the transformed {@link Attempt} diff --git a/src/test/java/org/pacien/lemonad/attempt/AttemptTest.java b/src/test/java/org/pacien/lemonad/attempt/AttemptTest.java index 6d87335..bb367dc 100644 --- a/src/test/java/org/pacien/lemonad/attempt/AttemptTest.java +++ b/src/test/java/org/pacien/lemonad/attempt/AttemptTest.java @@ -81,10 +81,12 @@ class AttemptTest { @Test void testTransformationFlow() { var result0 = 0; var result1 = "res"; - var result2 = 0L; - var fault0 = 0; - var fault1 = 1; - var fault2 = 2; + var result2 = true; + var result3 = 0L; + var fault0 = 0L; + var fault1 = 0; + var fault2 = "fail"; + var fault3 = false; Attempt.success(result0) .mapError(__ -> fail()) @@ -109,6 +111,9 @@ class AttemptTest { return Attempt.failure(fault2); }) .ifSuccess(__ -> fail()) - .ifFailure(f -> assertEquals(fault2, f)); + .ifFailure(f -> assertEquals(fault2, f)) + .map(__ -> Attempt.failure(fault3), __ -> Attempt.success(result3)) + .ifSuccess(result -> assertEquals(result3, result)) + .ifFailure(__ -> fail()); } } -- cgit v1.2.3