Diamond in type patterns?

Brian Goetz brian.goetz at oracle.com
Mon Jan 4 15:28:48 UTC 2021


In going through the JDK for places where we might use type patterns, I 
came across this example, from the copy construct of `EnumMap`:

```
public EnumMap(Map<K, ? extends V> m) {
     if (m instanceof EnumMap) {
         EnumMap<K, ? extends V> em = (EnumMap<K, ? extends V>) m;
         // optimized copy of map state from em
     } else {
         // insert elements one by one
     }
}
```

We can of course use a pattern match here, but we have to provide the 
fussy type:

```
public EnumMap(Map<K, ? extends V> m) {
     if (m instanceof EnumMap<K, ? extends V> em) {
         // optimized copy of map state from em
     } else {
         // insert elements one by one
     }
}
```

Arguably, we missed something here.  When we match against a type 
pattern `Foo<TVARS>`, there are two tests:

  - Is the dynamic type a `Foo`
  - Are the proposed type vars consistent with what we statically know

In other words, is the dynamic test we can do with `CHECKCAST` enough to 
infer the rest of the type?  The runtime does the dynamic part, and the 
compiler does the static part and then erases it.

We could have allowed (if we'd thought of it) the test to proceed as:

     if (m instanceof EnumMap em) { ... }

and inferred the type parameters, as we do with method references (e.g., 
`Function<String,String> f = Map::get`, where we infer 
`Map<String,String>` on the LHS of the colons.)  But, we didn't do that, 
so the `EnumMap` here is a raw type, and (should) garner a raw warning.  
(Does it?)

But if we can't do that, we can do the next best thing: allow diamond here:

     if (m instanceof EnumMap<> em) { ... }



-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.java.net/pipermail/amber-spec-experts/attachments/20210104/6bd4419a/attachment.htm>


More information about the amber-spec-experts mailing list