Added fromRight/fromLeft methods and unit tests

This commit is contained in:
Marco Cetica 2024-09-18 12:03:10 +02:00
parent b2084b6df9
commit 4bdd2278a7
Signed by: marco
GPG Key ID: 45060A949E90D0FD
5 changed files with 62 additions and 0 deletions

View File

@ -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);
}

View File

@ -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;
}
}

View File

@ -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;
}
}

View File

@ -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);
}
}

View File

@ -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);
}
}