Читать книгу OCP Oracle Certified Professional Java SE 17 Developer Study Guide - Jeanne Boyarsky - Страница 176

Shortening Code with Pattern Matching

Оглавление

Java 16 officially introduced pattern matching with if statements and the instanceof operator. Pattern matching is a technique of controlling program flow that only executes a section of code that meets certain criteria. It is used in conjunction with if statements for greater program control.

If pattern matching is new to you, be careful not to confuse it with the Java Pattern class or regular expressions (regex). While pattern matching can include the use of regular expressions for filtering, they are unrelated concepts.

Pattern matching is a new tool at your disposal to reduce boilerplate in your code. Boilerplate code is code that tends to be duplicated throughout a section of code over and over again in a similar manner. A lot of the newer enhancements to the Java language focus on reducing boilerplate code.

To understand why this tool was added, consider the following code that takes a Number instance and compares it with the value 5. If you haven't seen Number or Integer, you just need to know that Integer inherits from Number for now. You'll see them a lot in this book!

void compareIntegers(Number number) { if(number instanceof Integer) { Integer data = (Integer)number; System.out.print(data.compareTo(5)); } }

The cast is needed since the compareTo() method is defined on Integer, but not on Number.

Code that first checks if a variable is of a particular type and then immediately casts it to that type is extremely common in the Java world. It's so common that the authors of Java decided to implement a shorter syntax for it:

void compareIntegers(Number number) { if(number instanceof Integer data) { System.out.print(data.compareTo(5)); } }

The variable data in this example is referred to as the pattern variable. Notice that this code also avoids any potential ClassCastException because the cast operation is executed only if the implicit instanceof operator returns true.

OCP Oracle Certified Professional Java SE 17 Developer Study Guide

Подняться наверх