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

Flow Scoping and else Branches

Оглавление

If the last code sample confuses you, don't worry: you're not alone! Another way to think about it is to rewrite the logic to something equivalent that uses an else statement:

void printOnlyIntegers(Number number) { if (!(number instanceof Integer data)) return; else System.out.print(data.intValue()); }

We can now go one step further and reverse the if and else branches by inverting the boolean expression:

void printOnlyIntegers(Number number) { if (number instanceof Integer data) System.out.print(data.intValue()); else return; }

Our new code is equivalent to our original and better demonstrates how the compiler was able to determine that data was in scope only when number is an Integer.

Make sure you understand the way flow scoping works. In particular, it is possible to use a pattern variable outside of the if statement, but only when the compiler can definitively determine its type.

OCP Oracle Certified Professional Java SE 17 Developer Study Guide

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