Add Result.of(Callable) to reduce boiler plate when calling

This commit is contained in:
Paul Campbell 2018-06-30 16:21:07 +01:00
parent 74776975d2
commit 248bda0b4f
2 changed files with 48 additions and 0 deletions

View file

@ -24,6 +24,7 @@ package net.kemitix.mon.result;
import net.kemitix.mon.Functor; import net.kemitix.mon.Functor;
import net.kemitix.mon.maybe.Maybe; import net.kemitix.mon.maybe.Maybe;
import java.util.concurrent.Callable;
import java.util.function.Consumer; import java.util.function.Consumer;
import java.util.function.Function; import java.util.function.Function;
import java.util.function.Predicate; import java.util.function.Predicate;
@ -73,6 +74,22 @@ public interface Result<T> extends Functor<T, Result<?>> {
return new Success<>(value); return new Success<>(value);
} }
/**
* Create a Result for a output of the Callable.
*
* @param callable the callable to produce the result
* @param <T> the type of the value
* @return a Result
*/
@SuppressWarnings("illegalcatch")
static <T> Result<T> of(final Callable<T> callable) {
try {
return Result.ok(callable.call());
} catch (final Exception e) {
return Result.error(e);
}
}
/** /**
* Creates a Result from the Maybe, where the Result will be an error if the Maybe is Nothing. * Creates a Result from the Maybe, where the Result will be an error if the Maybe is Nothing.
* *

View file

@ -6,6 +6,9 @@ import net.kemitix.mon.result.Result;
import org.assertj.core.api.WithAssertions; import org.assertj.core.api.WithAssertions;
import org.junit.Test; import org.junit.Test;
import java.io.IOException;
import java.util.concurrent.Callable;
public class ResultTest implements WithAssertions { public class ResultTest implements WithAssertions {
@Test @Test
@ -396,6 +399,34 @@ public class ResultTest implements WithAssertions {
assertThat(toString).contains("Result.Error{error=java.lang.RuntimeException: failed}"); assertThat(toString).contains("Result.Error{error=java.lang.RuntimeException: failed}");
} }
@Test
public void resultOf_okay_isOkay() {
//given
final Callable<String> c = () -> "okay";
//when
final Result<String> result = Result.of(c);
//then
result.match(
success -> assertThat(success).isEqualTo("okay"),
error -> fail("not an error")
);
}
@Test
public void resultOf_error_isError() {
//given
final Callable<String> c = () -> {
throw new IOException();
};
//when
final Result<String> result = Result.of(c);
//then
result.match(
success -> fail("not a success"),
error -> assertThat(error).isInstanceOf(IOException.class)
);
}
@RequiredArgsConstructor @RequiredArgsConstructor
private static class UseCase { private static class UseCase {