Added swap method and unit tests

This commit is contained in:
Marco Cetica 2024-09-18 16:27:13 +02:00
parent a20ecbbaa5
commit 284035e57b
Signed by: marco
GPG Key ID: 45060A949E90D0FD
5 changed files with 35 additions and 1 deletions

View File

@ -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
* <i>onRight</i> function to the <i>Right</i> subtype.
* </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
* @return An <i>Either</i> functor
* @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
*/
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();
}

View File

@ -52,4 +52,9 @@ public record Left<L, R>(L value) implements Either<L, R> {
public Optional<R> toOptional() {
return Optional.empty();
}
@Override
public Either<R, L> swap() {
return new Right<>(this.value);
}
}

View File

@ -52,4 +52,9 @@ public record Right<L, R>(R value) implements Either<L, R> {
public Optional<R> toOptional() {
return Optional.of(this.value);
}
@Override
public Either<R, L> swap() {
return new Left<>(this.value);
}
}

View File

@ -103,4 +103,12 @@ public class LeftTests {
Optional.empty()
);
}
@Test
public void testSwapFromLeft() {
assertEquals(
this.resEither.swap(),
new Right<>(19)
);
}
}

View File

@ -103,4 +103,12 @@ public class RightTests {
Optional.of(4)
);
}
@Test
public void testSwapFromRight() {
assertEquals(
this.numEither.swap(),
new Left<>(4)
);
}
}