Debian Codegraph @

checker/tests/nullness/flow/TestOpt.java

raw
1 import org.checkerframework.checker.nullness.Opt;
2 import org.checkerframework.checker.nullness.qual.*;
3
4 /** Test class org.checkerframework.checker.nullness.Opt. */
5 class TestOpt {
6 void foo1(@Nullable Object p) {
7 if (Opt.isPresent(p)) {
8 p.toString(); // Flow refinement
9 }
10 }
11
12 void foo1b(@Nullable Object p) {
13 if (!Opt.isPresent(p)) {
14 // :: error: (dereference.of.nullable)
15 p.toString();
16 }
17 }
18
19 void foo2(@Nullable Object p) {
20 Opt.ifPresent(p, x -> System.out.println("Got: " + x));
21 }
22
23 void foo2b(@Nullable Object p) {
24 Opt.ifPresent(p, x -> System.out.println("Got: " + x.toString()));
25 }
26
27 void foo3(@Nullable Object p) {
28 Object o = Opt.filter(p, x -> x.hashCode() > 10);
29 }
30
31 void foo4(@Nullable Object p) {
32 String s = Opt.map(p, x -> x.toString());
33 }
34
35 void foo4b(@Nullable Object p) {
36 // :: error: (argument.type.incompatible)
37 String s = Opt.map(p, null);
38 }
39
40 void foo5(@Nullable Object p) {
41 @NonNull Object o = Opt.orElse(p, new Object());
42 }
43
44 void foo5b(@Nullable Object p) {
45 // :: error: (argument.type.incompatible)
46 @NonNull Object o = Opt.orElse(p, null);
47 }
48
49 void foo6(@Nullable Object p) {
50 @NonNull Object o = Opt.orElseGet(p, () -> new Object());
51 }
52
53 void foo6b(@Nullable Object p) {
54 // :: error: (return.type.incompatible)
55 @NonNull Object o = Opt.orElseGet(p, () -> null);
56 }
57
58 void foo7(Object p) {
59 try {
60 @NonNull Object o = Opt.orElseThrow(p, () -> new Throwable());
61 } catch (Throwable t) {
62 // p was null
63 }
64 }
65
66 void foo7b(@Nullable Object p) {
67 try {
68 // :: error: (assignment.type.incompatible) :: error: (type.argument.type.incompatible)
69 // :: error: (return.type.incompatible)
70 @NonNull Object o = Opt.orElseThrow(p, () -> null);
71 } catch (Throwable t) {
72 // p was null
73 }
74 }
75 }