Java 24 introduces enhancements to pattern matching by allowing primitive types in all pattern contexts, and extending instanceof
and switch
to work with all primitive types. This is a preview language feature.
Previously, pattern matching for switch
only supported reference types such as Integer i
, but now it supports primitive types too. For example:
int i = 100; String s = switch(i) { case 1 -> "one"; case 2 -> "two"; case int i when i > 2 -> "too big"; default -> "unsupported"; }
Similarly, instanceof
has been enhanced to support primitives, as shown in the example below:
int i = 1; if (i instanceof byte b) { // i has been cast to byte and assigned to b }Related posts:
Java 19: Record Patterns
Java 17: Pattern Matching for Switch
Java 14: Pattern Matching for instanceof
No comments:
Post a Comment
Note: Only a member of this blog may post a comment.