Skip to content

Commit

Permalink
Add Either#from
Browse files Browse the repository at this point in the history
  • Loading branch information
2bllw8 committed Jul 3, 2022
1 parent 5231010 commit 8b6210e
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
17 changes: 17 additions & 0 deletions lib/src/main/java/exe/bbllw8/either/Either.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
import java.util.Optional;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Stream;

/**
Expand All @@ -19,6 +20,8 @@
* <ul>
* <li>{@link Left}: instance with a left value</li>
* <li>{@link Right}: instance with a right value</li>
* <li>{@link Either#from(boolean, Supplier, Supplier)}: instance from the evaluation
* of a supplied boolean value</li>
* </ul>
* <p>
* This class is not serializable.
Expand All @@ -37,6 +40,7 @@ public abstract class Either<A, B> {
* <ul>
* <li>{@link Left}</li>
* <li>{@link Right}</li>
* <li>{@link Either#from(boolean, Supplier, Supplier)}</li>
* </ul>
*
* @hidden
Expand Down Expand Up @@ -174,6 +178,19 @@ public abstract class Either<A, B> {
*/
public abstract Optional<B> toOptional();

/**
* @return If the <code>conditional</code> is <code>true</code> returns a {@link Right} holding
* the value supplied by <code>ifTrue</code>, otherwise a {@link Left} holding the value
* supplied by the <code>ifFalse</code>
* @since 3.4.0
*/
public static <A, B> Either<A, B> from(boolean conditional, Supplier<B> ifTrue,
Supplier<A> ifFalse) {
return conditional
? new Right<>(ifTrue.get())
: new Left<>(ifFalse.get());
}

/**
* @return Returns the right value if the given argument is {@link Right} or its value if it is
* {@link Left}.
Expand Down
25 changes: 25 additions & 0 deletions lib/src/test/java/exe/bbllw8/either/EitherTest.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
/*
* Copyright (c) 2022 2bllw8
* SPDX-License-Identifier: Apache-2.0
*/
package exe.bbllw8.either;

import org.junit.Assert;
import org.junit.Test;

public final class EitherTest {

@Test
public void from() {
Assert.assertTrue("Should return a Right if the conditional supplies a true value",
Either.from(true, () -> 0, () -> 0) instanceof Right);
Assert.assertTrue("Should return a Left if the conditional supplies a false value",
Either.from(false, () -> 0, () -> 0) instanceof Left);
Assert.assertEquals("Should return the value supplied by the ifTrue parameter",
new Right<>(1),
Either.from(true, () -> 1, () -> 0));
Assert.assertEquals("Should return the value supplied by the ifFalse parameter",
new Left<>(0),
Either.from(false, () -> 1, () -> 0));
}
}

0 comments on commit 8b6210e

Please sign in to comment.