Added swap method and unit tests
This commit is contained in:
parent
a20ecbbaa5
commit
284035e57b
@ -70,7 +70,7 @@ public sealed interface Either<L, R> permits Left, Right {
|
|||||||
* Applies <i>onLeft</i> function to the <i>Left</i> subtype or the
|
* Applies <i>onLeft</i> function to the <i>Left</i> subtype or the
|
||||||
* <i>onRight</i> function to the <i>Right</i> subtype.
|
* <i>onRight</i> function to the <i>Right</i> subtype.
|
||||||
* </p>
|
* </p>
|
||||||
* @param onLeft The function to apply to the <i>Left</i> subtyp
|
* @param onLeft The function to apply to the <i>Left</i> subtype
|
||||||
* @param onRight The function to apply to the <i>Right</i> subtype
|
* @param onRight The function to apply to the <i>Right</i> subtype
|
||||||
* @return An <i>Either</i> functor
|
* @return An <i>Either</i> functor
|
||||||
* @param <T> The return type of the <i>onLeft</i> function
|
* @param <T> The return type of the <i>onLeft</i> function
|
||||||
@ -109,4 +109,12 @@ public sealed interface Either<L, R> permits Left, Right {
|
|||||||
* @return An <i>Optional</i> data type
|
* @return An <i>Optional</i> data type
|
||||||
*/
|
*/
|
||||||
Optional<R> toOptional();
|
Optional<R> toOptional();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* <p>
|
||||||
|
* Flips the <i>Left</i> and the <i>Right</i> data types.
|
||||||
|
* </p>
|
||||||
|
* @return An <i>Either</i> monad with <i>Left</i> and <i>Right</i> flipped
|
||||||
|
*/
|
||||||
|
Either<R, L> swap();
|
||||||
}
|
}
|
@ -52,4 +52,9 @@ public record Left<L, R>(L value) implements Either<L, R> {
|
|||||||
public Optional<R> toOptional() {
|
public Optional<R> toOptional() {
|
||||||
return Optional.empty();
|
return Optional.empty();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Either<R, L> swap() {
|
||||||
|
return new Right<>(this.value);
|
||||||
|
}
|
||||||
}
|
}
|
@ -52,4 +52,9 @@ public record Right<L, R>(R value) implements Either<L, R> {
|
|||||||
public Optional<R> toOptional() {
|
public Optional<R> toOptional() {
|
||||||
return Optional.of(this.value);
|
return Optional.of(this.value);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public Either<R, L> swap() {
|
||||||
|
return new Left<>(this.value);
|
||||||
|
}
|
||||||
}
|
}
|
@ -103,4 +103,12 @@ public class LeftTests {
|
|||||||
Optional.empty()
|
Optional.empty()
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testSwapFromLeft() {
|
||||||
|
assertEquals(
|
||||||
|
this.resEither.swap(),
|
||||||
|
new Right<>(19)
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -103,4 +103,12 @@ public class RightTests {
|
|||||||
Optional.of(4)
|
Optional.of(4)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@Test
|
||||||
|
public void testSwapFromRight() {
|
||||||
|
assertEquals(
|
||||||
|
this.numEither.swap(),
|
||||||
|
new Left<>(4)
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
Loading…
Reference in New Issue
Block a user