March 2019
Intermediate to advanced
242 pages
6h 21m
English
To get around the issues created by the testing-casting-instance destruction pattern, Java proposes to embrace pattern matching.
Here's an example of the proposed changes to the language:
Object obj = new Ocean(); // variable type - Object
if (obj matches Ocean o) { // check & bind
System.out.println(o.getBottles()); // extract
}
The preceding code introduces a new Java keyword, matches, which includes a predicate (obj) and a target (Ocean o). The predicate, that is, obj is applied to the target, that is, Ocean o, which binds the o variable to the instance referred by obj. If the matching is successful, you can access members of the instance using the bound variable, that is, o. The following diagram compares the code ...
Read now
Unlock full access