Skip to content

Commit

Permalink
Update JavaExamples with more examples
Browse files Browse the repository at this point in the history
  • Loading branch information
txiang61 authored Apr 26, 2024
1 parent c843a86 commit 10a07e3
Showing 1 changed file with 16 additions and 12 deletions.
28 changes: 16 additions & 12 deletions JavaExamples → JavaExamples.java
Original file line number Diff line number Diff line change
@@ -1,39 +1,43 @@
/// Java Examples
import java.util.*;
import qual.Mutable;

// Mutating immut set, `s` is immut
void foo(Set<String> s) {
Set<String> new_s = s;
@Mutable Set<String> new_s1 = s; // ERROR
new_s.add("x"); // ERROR
}

// Mutating immut set, `new_s` is immut
void foo(@Mutable Set<String> s) {
void foo1(@Mutable Set<String> s) {
Set<String> new_s = new HashSet<>(s);
new_s.add("x"); // ERROR
}

// Mutating mut set
void foo(Set<String> s) {
void foo2(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) {
void foo3(Set<List<String>> s, List<String> l) {
assert s.get(l) != null;
List<String> v = s.get(l);
l.add("x"); // ERROR
@Mutable List<String> v2 = s.get(l); // ERROR
v.add("x"); // ERROR
}

// Immut class and its members
// Class and its immut members
class Person {
String name;
List<String> family;

Person(String n, List<String> f) {
this.name = n; // OK
this.family = f; // OK
this.family.add("Mom"); // ERROR
}

void setName(String n) {
Expand All @@ -45,20 +49,21 @@ void setName(String n) {
}
}

void foo(Person p) {
void foo4(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;
// Class and its mut members
class MutPerson {
@Mutable String name;
@Mutable List<String> family;

Person(String n, List<String> f) {
this.name = n; // OK
this.family = f; // OK
this.family.add("Mom"); // OK
}

void setName(String n) {
Expand All @@ -70,9 +75,8 @@ List<String> getFamily() {
}
}

void foo(Person p) {
void foo5(MutPerson p) {
p.name = "Jenny"; // OK
p.family.add("Jenny"); // OK
p.family.getFamily().add("Jenny"); // ERROR
}

0 comments on commit 10a07e3

Please sign in to comment.