-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathJavaExamples
More file actions
78 lines (63 loc) · 1.42 KB
/
JavaExamples
File metadata and controls
78 lines (63 loc) · 1.42 KB
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
/// Java Examples
// Mutating immut set, `s` is immut
void foo(Set<String> s) {
Set<String> new_s = s;
new_s.add("x"); // ERROR
}
// Mutating immut set, `new_s` is immut
void foo(@Mutable Set<String> s) {
Set<String> new_s = new HashSet<>(s);
new_s.add("x"); // ERROR
}
// Mutating mut set
void foo(Set<String> s) {
@Mutable Set<String> new_s = new HashSet<>(s);
new_s.add("x"); // OK
}
// Type parameter mutability
void foo(Set<List<String>> s, List<String> l) {
assert s.get(l) != null;
List<String> v = s.get(l);
l.add("x"); // ERROR
v.add("x"); // ERROR
}
// Immut class and its members
class Person {
String name;
List<String> family;
Person(String n, List<String> f) {
this.name = n; // OK
this.family = f; // OK
}
void setName(String n) {
this.name = n; // ERROR
}
@Mutable List<String> getFamily() {
return family; // ERROR
}
}
void foo(Person p) {
p.name = "Jenny"; // ERROR
p.family.add("Jenny"); // ERROR
p.family.getFamily().add("Jenny"); // OK
}
// Mut class and its members
@Mutable class Person {
String name;
List<String> family;
Person(String n, List<String> f) {
this.name = n; // OK
this.family = f; // OK
}
void setName(String n) {
this.name = n; // OK
}
List<String> getFamily() {
return family; // OK
}
}
void foo(Person p) {
p.name = "Jenny"; // OK
p.family.add("Jenny"); // OK
p.family.getFamily().add("Jenny"); // ERROR
}