Either usage example.
This commit is contained in:
parent
979d80a56a
commit
ad3998bb61
@ -0,0 +1,37 @@
|
|||||||
|
package pl.amu.edu.demo.either;
|
||||||
|
|
||||||
|
import io.vavr.control.Either;
|
||||||
|
import pl.amu.edu.demo.data.Person;
|
||||||
|
|
||||||
|
import java.time.LocalDate;
|
||||||
|
|
||||||
|
import static java.util.Objects.isNull;
|
||||||
|
|
||||||
|
public class EitherExample {
|
||||||
|
|
||||||
|
public static void main(String[] args) {
|
||||||
|
new EitherExample().run();
|
||||||
|
}
|
||||||
|
|
||||||
|
private void run() {
|
||||||
|
var balbina = Person.builder()
|
||||||
|
.displayName("Gąska Balbinka").birthDate(LocalDate.ofYearDay(1959, 1)).build();
|
||||||
|
var poziomka = Person.builder()
|
||||||
|
.displayName("magic Poziomka").build();
|
||||||
|
var maybeBalbinasAge = getAge(balbina);
|
||||||
|
var maybePoziomkasAge = getAge(poziomka);
|
||||||
|
System.out.printf("Is Balbinas age empty? %s\n", maybeBalbinasAge.isEmpty());
|
||||||
|
System.out.printf("Is Poziomkas age empty? %s\n", maybePoziomkasAge.isEmpty());
|
||||||
|
System.out.printf("Balbinas age: %d\n", maybeBalbinasAge.get());
|
||||||
|
System.out.printf("Poziomkas error: %s\n", maybePoziomkasAge.getLeft());
|
||||||
|
}
|
||||||
|
|
||||||
|
private Either<ProcessingError, Integer> getAge(Person person) {
|
||||||
|
if (isNull(person.birthDate)) {
|
||||||
|
// konwencja: błędy po lewej
|
||||||
|
return Either.left(ProcessingError.of("No birthdate!"));
|
||||||
|
}
|
||||||
|
return Either.right(person.getAge());
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
Loading…
Reference in New Issue
Block a user