r/java • u/Joram2 • Mar 17 '22
Record Patterns Officially Planned as Preview Feature for JDK 19
Record Patterns, are coming as a preview feature to JDK 19. The official JEP has been updated to say
> This is a preview language feature in JDK 19.
(https://openjdk.java.net/jeps/405)
Code Example:
int eval(Expr n) {
return switch(n) {
case IntExpr(int i) -> i;
case NegExpr(Expr n) -> -eval(n);
case AddExpr(Expr left, Expr right) -> eval(left) + eval(right);
case MulExpr(Expr left, Expr right) -> eval(left) * eval(right);
default -> throw new IllegalArgumentException(n);
};
}2
u/Kango_V Mar 20 '22
A question about types:
record Point(int x, int y) {}
void printSum(Object o) {
if (o instanceof Point(int x, int y)) {
System.out.println(x+y);
}
}Why do you need to specify the types for x and y in the deconstruction. Why could you not just have:
if (o instanceof Point(x, y)) {
System.out.println(x+y);
}Surely the compiler knows the types and can infer them?
3
u/Joram2 Mar 20 '22
The JEP does say:
A record pattern can use var to match against a record component without stating the type of the component. In this case, the compiler infers the type of the pattern variable introduced by the var pattern. For example, the pattern Point(var a, var b) is shorthand for the pattern Point(int a, int b).
So it will infer the types. As for why you need to do Point(var a, var b) rather than just Point(a, b), I don't know.
1
u/JMasterRedBlaze Mar 20 '22
I think that's because in Java you have to first declare the variable and then assign a value to it, if the variable is not declared it will give an error.
The var keyword was added to infer values ​​so I think you could do the following:
if (o instanceof Point(var x, var y)) {System.out.println(x+y);}
33
u/testube_babies Mar 17 '22
Looking forward to this. Use it all the time in Scala. Currently using VAVR in Java but pattern matching is a bit cumbersome.
8
u/Holothuroid Mar 17 '22
What's still missing is an opt in for other classes, as Scala's
.unapply.11
u/dpash Mar 18 '22
It's coming. Deconstructors for classes is on the to-do list.
Once that happens it opens up things like an improved serialisation mechanism.
3
7
u/[deleted] Mar 17 '22
How long until they make public the full feature list? Page is currently low on info.
https://openjdk.java.net/projects/jdk/19/