From ad3998bb61214f8d0e76a79a0250f3644834de4b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Pawe=C5=82=20Dyda?= Date: Thu, 17 Nov 2022 14:46:47 +0100 Subject: [PATCH] Either usage example. --- .../pl/amu/edu/demo/either/EitherExample.java | 37 +++++++++++++++++++ 1 file changed, 37 insertions(+) create mode 100644 demo/03/src/main/java/pl/amu/edu/demo/either/EitherExample.java diff --git a/demo/03/src/main/java/pl/amu/edu/demo/either/EitherExample.java b/demo/03/src/main/java/pl/amu/edu/demo/either/EitherExample.java new file mode 100644 index 0000000..abbdf37 --- /dev/null +++ b/demo/03/src/main/java/pl/amu/edu/demo/either/EitherExample.java @@ -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 getAge(Person person) { + if (isNull(person.birthDate)) { + // konwencja: błędy po lewej + return Either.left(ProcessingError.of("No birthdate!")); + } + return Either.right(person.getAge()); + } + +}