Draft JLS spec for JEP 305: Pattern matching for instanceof

Brian Goetz brian.goetz at oracle.com
Fri Sep 20 14:12:48 UTC 2019

> 1. The instanceof operator restricts the type to be a reifiable reference type. The spec currently keeps that restriction for type test patterns too. But should we go further, i.e. will people expect to be able to say the following (given that this *declares* a pattern variable l)?
> if (o instanceof List<Integer> l) {
>> } 
> If we allow such case, the compiler will have to emit an unchecked warning because this code is not safe.

This is not correct.  If you look at what I wrote in 

    http://cr.openjdk.java.net/~briangoetz/amber/pattern-semantics.html <http://cr.openjdk.java.net/~briangoetz/amber/pattern-semantics.html>

it is possible to do this in a safe manner, by appealing to whether the cast conversion is checked or not:

Generic type patterns are permitted (this is a relaxation of the current semantics of the instanceof operator, which requires that the type operand is reifiable.) However, when determining applicability involves cast conversions, the pattern is not applicable if the cast conversion would be unchecked. So it is allowable to say

List<Integer> list = ...
if (list instanceof ArrayList<Integer> a) { ... }
but not

List<?> list = ...
if (list instanceof ArrayList<String> a) { ... }

So if we permitted non-reifiable types in type patterns, it would only be where a cast conversion would not produced an unchecked warning, and this is not unsafe.  

More information about the amber-spec-observers mailing list