From the course: Java SE 21 Developer (1Z0-830) Cert Prep

Unlock this course with a free trial

Join today to access over 25,600 courses taught by industry experts.

Pattern matching with switch: Handling records

Pattern matching with switch: Handling records - Java Tutorial

From the course: Java SE 21 Developer (1Z0-830) Cert Prep

Pattern matching with switch: Handling records

- Now, the pattern-matching system can actually extract the values of record components. Now, all the component elements must be matched with a variable declaration. You can't just select one or two of those components and ignore the rest of them, you have to match them all, but you don't have to use all the matched elements. You do have to put them in a variable in Java 21. So here, we see an example. Assume that we have a customer record type which has a name, which is a string. Perhaps this is a credit limit or something, which is an int, and the third member, the third component of this is a local date. We can switch on that customer type and then we can have case Customer, and notice we extract String n. That will pull out Inaya. Int cl, that will match the credit limit and pull out the value 10000, and the LocalDate s, which will pull out this 2019, 4, 12. Then we can use any of those fields in a when clause.…

Contents