-
-
Notifications
You must be signed in to change notification settings - Fork 112
Expand file tree
/
Copy pathJava16Records.java
More file actions
69 lines (55 loc) · 2.05 KB
/
Copy pathJava16Records.java
File metadata and controls
69 lines (55 loc) · 2.05 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
/// Expect:
/// - output: "1, 2\n3\nsame=True\ndiff=False\norigin=0\nCircle r=2\nlabel=P\nrange=1..50\ncaught=yes\n"
package example;
// https://docs.oracle.com/en/java/javase/16/language/records.html
interface Shape {
public String describe();
}
record Circle(int radius) implements Shape {
public String describe() {
return "Circle r=" + radius;
}
}
public class Program {
// Members are declared public because Java's package-private default maps to C# private,
// which is a pre-existing converter behavior unrelated to records.
public record Point(int x, int y) {
public static final Point ORIGIN = new Point(0, 0);
public int sum() {
return x + y;
}
}
public record Labeled<T>(String label, T value) {
}
// The compact constructor validates and normalizes the components. Its body runs against the
// parameters, and the components are assigned from them afterwards.
public record Range(int low, int high) {
public Range {
if (low > high) {
throw new IllegalArgumentException("low > high");
}
high = high * 10;
}
}
public static void main(String[] args) {
Point p = new Point(1, 2);
System.out.println(p.x + ", " + p.y);
System.out.println(p.sum());
// Records have value equality in both languages.
System.out.println("same=" + p.equals(new Point(1, 2)));
System.out.println("diff=" + p.equals(new Point(3, 4)));
System.out.println("origin=" + Point.ORIGIN.sum());
Shape s = new Circle(2);
System.out.println(s.describe());
Labeled<Integer> labeled = new Labeled<Integer>("P", 42);
System.out.println("label=" + labeled.label);
Range r = new Range(1, 5);
System.out.println("range=" + r.low + ".." + r.high);
try {
new Range(9, 2);
System.out.println("caught=no");
} catch (IllegalArgumentException e) {
System.out.println("caught=yes");
}
}
}