Added toOptional method and unit tests

This commit is contained in:
Marco Cetica 2024-09-18 16:19:41 +02:00
parent 6eabe26105
commit a20ecbbaa5
Signed by: marco
GPG Key ID: 45060A949E90D0FD
5 changed files with 40 additions and 0 deletions

View File

@ -1,5 +1,6 @@
package com.ceticamarco.lambdatonic;
import java.util.Optional;
import java.util.function.Function;
/**
@ -99,4 +100,13 @@ public sealed interface Either<L, R> permits Left, Right {
*/
L fromLeft(L defaultValue);
/**
* <p>
* Converts an <i>Either</i> data type to a <i>java.util.Optional</i>.
* The <i>Right</i> becomes a non-null <i>Optional</i> and the <i>Left</i>
* becomes a null <i>Optional</i>
* </p>
* @return An <i>Optional</i> data type
*/
Optional<R> toOptional();
}

View File

@ -1,5 +1,6 @@
package com.ceticamarco.lambdatonic;
import java.util.Optional;
import java.util.function.Function;
/**
@ -46,4 +47,9 @@ public record Left<L, R>(L value) implements Either<L, R> {
public L fromLeft(L defaultValue) {
return this.value;
}
@Override
public Optional<R> toOptional() {
return Optional.empty();
}
}

View File

@ -1,5 +1,6 @@
package com.ceticamarco.lambdatonic;
import java.util.Optional;
import java.util.function.Function;
/**
@ -46,4 +47,9 @@ public record Right<L, R>(R value) implements Either<L, R> {
public L fromLeft(L defaultValue) {
return defaultValue;
}
@Override
public Optional<R> toOptional() {
return Optional.of(this.value);
}
}

View File

@ -3,6 +3,7 @@ package com.ceticamarco.lambdatonic;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.BeforeEach;
import java.util.Optional;
import java.util.function.Function;
import static org.junit.jupiter.api.Assertions.assertEquals;
@ -94,4 +95,12 @@ public class LeftTests {
public void testFromLeftOnLeft() {
assertEquals(this.resEither.fromLeft(-1), 19);
}
@Test
public void testToOptionalFromLeft() {
assertEquals(
this.numEither.toOptional(),
Optional.empty()
);
}
}

View File

@ -3,6 +3,7 @@ package com.ceticamarco.lambdatonic;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.BeforeEach;
import java.util.Optional;
import java.util.function.Function;
import static org.junit.jupiter.api.Assertions.assertEquals;
@ -94,4 +95,12 @@ public class RightTests {
public void testFromLeftOnRight() {
assertEquals(this.resEither.fromLeft(-1), -1);
}
@Test
public void testToOptionalFromRight() {
assertEquals(
this.numEither.toOptional(),
Optional.of(4)
);
}
}