Skip to content

Commit a87f9bf

Browse files
committed
Validation with Either
1 parent 5ba034e commit a87f9bf

1 file changed

Lines changed: 17 additions & 0 deletions

File tree

src/main/java/org/kunicki/functional_java/Validation.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,7 @@
11
package org.kunicki.functional_java;
22

3+
import io.vavr.control.Either;
4+
35
record Person(String name, int age) {
46
}
57

@@ -18,6 +20,21 @@ default boolean isAgeValid(int age) {
1820

1921
class FailingFast implements PersonValidator {
2022

23+
private Either<String, String> validateName(String name) {
24+
return isNameValid(name) ? Either.right(name) : Either.left("Invalid name");
25+
}
26+
27+
private Either<String, Integer> validateAge(int age) {
28+
return isAgeValid(age) ? Either.right(age) : Either.left("Invalid age");
29+
}
30+
31+
public Either<String, Person> validate(String name, int age) {
32+
return validateName(name).flatMap(n ->
33+
validateAge(age).map(a ->
34+
new Person(n, a)
35+
)
36+
);
37+
}
2138
}
2239

2340
class Accumulating implements PersonValidator {

0 commit comments

Comments
 (0)