Added toOptional method and unit tests
This commit is contained in:
parent
6eabe26105
commit
a20ecbbaa5
@ -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();
|
||||
}
|
@ -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();
|
||||
}
|
||||
}
|
@ -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);
|
||||
}
|
||||
}
|
@ -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()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
@ -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)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user