-
-
Notifications
You must be signed in to change notification settings - Fork 57
/
VavrPatternMatching.java
82 lines (69 loc) · 1.97 KB
/
VavrPatternMatching.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package vavr;
import io.vavr.Predicates;
import io.vavr.control.Either;
import io.vavr.control.Option;
import io.vavr.control.Try;
import org.junit.Test;
import static io.vavr.API.*;
import static io.vavr.Patterns.*;
import static io.vavr.Predicates.*;
public class VavrPatternMatching {
@Test
public void optionPattern() {
var option = Option.of("hello world");
var output = Match(option).of(
Case($Some($()), value -> "defined"),
Case($None(), "empty")
);
println(output);
}
@Test
public void tryPattern() {
var output = Match(Try.of(() ->"hello world")).of(
Case($Success($()), value -> {
return "success";
}),
Case($Failure($(Predicates.instanceOf(NullPointerException.class))), e -> "error" + e)
);
println(output);
}
@Test
public void eitherPattern() {
var output = Match(Either.right("hello world")).of(
Case($Right($()), value -> {
return "success";
}),
Case($Left($(Predicates.instanceOf(NullPointerException.class))), e -> "error" + e)
);
println(output);
}
@Test
public void typeClassesPattern() {
Object obj = new A("Hello A");
String of = Match(obj).of(
Case($(instanceOf(A.class)), a -> a.a),
Case($(instanceOf(B.class)), b -> b.b)
);
System.out.println(of);
}
@Test
public void booleanPattern() {
var output = Match(false).of(
Case(($(true)), value -> "found"),
Case(($(false)), value -> "not found")
);
println(output);
}
static class A {
public A(String a) {
this.a = a;
}
public String a;
}
static class B {
public B(String b) {
this.b = b;
}
public String b;
}
}