Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 12 additions & 0 deletions src/main/java/com/jasongoodwin/monads/Try.java
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,18 @@ public static <U> Try<U> ofFailable(TrySupplier<U> f) {
}
}

public static <U> Try<U> ofOptional(Optional<U> op, Throwable e) {
if(op.isPresent()) {
return new Success<>(op.get());
} else {
return new Failure<>(e);
}
}

public static <U> Try<U> ofOptional(Optional<U> op) {
return ofOptional(op, new IllegalArgumentException("Missing Value"));
}

/**
* Transform success or pass on failure.
* Takes an optional type parameter of the new type.
Expand Down
14 changes: 14 additions & 0 deletions src/test/java/com/jasongoodwin/monads/TryTest.java
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,20 @@ public void itShouldThrowNewExceptionWhenInvokingOrElseThrowOnFailure() throws T
});
}

@Test
public void itShouldCreateSuccessFromPopulatedOptional() throws Throwable {
Try<String> t = Try.ofOptional(Optional.of("foobar"), new IllegalArgumentException("Missing Value"));
assertTrue(t.isSuccess());
assertEquals(t.get(), "foobar");
}

@Test(expected = IllegalArgumentException.class)
public void itShouldCreateFailureFromEmptyOptional() throws Throwable {
Try<String> t = Try.ofOptional(Optional.empty(), new IllegalArgumentException("Missing Value"));

t.get();
}

public void itShouldNotThrowNewExceptionWhenInvokingOrElseThrowOnSuccess() throws Throwable {
Try<String> t = Try.ofFailable(() -> "Ok");

Expand Down