-
Notifications
You must be signed in to change notification settings - Fork 65
/
Copy pathmonad2.java
44 lines (36 loc) · 1.23 KB
/
monad2.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package monad;
import monad.monad1.User;
import java.util.Objects;
import java.util.function.Predicate;
import java.util.stream.Stream;
public interface monad2 {
record User(String name, int age) { }
record Error(IllegalArgumentException e, Error next) { }
record Validator<V>(V value, Error error) {
public V orElseThrow() throws IllegalStateException {
if (error == null) {
return value;
}
var exception = new IllegalStateException();
Stream.iterate(error, Objects::nonNull, Error::next).map(Error::e).forEach(exception::addSuppressed);
throw exception;
}
public Validator<V> check(Predicate<? super V> validation, String message) {
if (!validation.test(value)) {
return new Validator<>(value, new Error(new IllegalArgumentException(message), error));
}
return this;
}
}
static User validateUser(User user) {
return new Validator<>(user, null)
.check(u -> !u.name().isEmpty(), "name is empty")
.check(u -> u.age() >= 0 && u.age() <= 150, "age is not between 0 and 150")
.orElseThrow();
}
static void main(String[] args) {
var user = new User("bob", 12);
//var user = new User("", -12);
validateUser(user);
}
}