Added fromRight/fromLeft methods and unit tests
This commit is contained in:
parent
b2084b6df9
commit
4bdd2278a7
@ -63,4 +63,26 @@ public sealed interface Either<L, R> permits Left, Right {
|
||||
* @param <T> The return type of the <i>fn</i> function
|
||||
*/
|
||||
<T> Either<L, T> map(Function<R, T> fn);
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Returns the content of <i>Right</i> or a default value
|
||||
* <br /><br />
|
||||
* The default value must be of the same type of the <i>Right</i> value
|
||||
* </p>
|
||||
* @param defaultValue The default value to return if <i>Either</i> is <i>Left</i>
|
||||
* @return The right value of <i>Either</i> or the default value
|
||||
*/
|
||||
R fromRight(R defaultValue);
|
||||
|
||||
/**
|
||||
* <p>
|
||||
* Returns the content of <i>Left</i> or a default value
|
||||
* <br /><br />
|
||||
* The default value must be of the same type of the <i>Left</i> value
|
||||
* </p>
|
||||
* @param defaultValue The default value to return if <i>Either</i> is <i>Right</i>
|
||||
* @return The left value of <i>Either</i> or the default value
|
||||
*/
|
||||
L fromLeft(L defaultValue);
|
||||
}
|
@ -31,4 +31,14 @@ public record Left<L, R>(L value) implements Either<L, R> {
|
||||
public <T> Either<L, T> map(Function<R, T> fn) {
|
||||
return new Left<>(this.value);
|
||||
}
|
||||
|
||||
@Override
|
||||
public R fromRight(R defaultValue) {
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
@Override
|
||||
public L fromLeft(L defaultValue) {
|
||||
return this.value;
|
||||
}
|
||||
}
|
@ -31,4 +31,14 @@ public record Right<L, R>(R value) implements Either<L, R> {
|
||||
public <T> Either<L, T> map(Function<R, T> fn) {
|
||||
return new Right<>(fn.apply(this.value));
|
||||
}
|
||||
|
||||
@Override
|
||||
public R fromRight(R defaultValue) {
|
||||
return this.value;
|
||||
}
|
||||
|
||||
@Override
|
||||
public L fromLeft(L defaultValue) {
|
||||
return defaultValue;
|
||||
}
|
||||
}
|
@ -74,4 +74,14 @@ public class LeftTests {
|
||||
|
||||
assertEquals(composition, FGMapped);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFromRightOnLeft() {
|
||||
assertEquals(this.numEither.fromRight(-1), -1);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFromLeftOnLeft() {
|
||||
assertEquals(this.resEither.fromLeft(-1), 19);
|
||||
}
|
||||
}
|
||||
|
@ -74,4 +74,14 @@ public class RightTests {
|
||||
|
||||
assertEquals(composition, FGMapped);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFromRightOnRight() {
|
||||
assertEquals(this.numEither.fromRight(-1), 4);
|
||||
}
|
||||
|
||||
@Test
|
||||
public void testFromLeftOnRight() {
|
||||
assertEquals(this.resEither.fromLeft(-1), -1);
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user