Diamond in type patterns?

Remi Forax forax at univ-mlv.fr
Mon Jan 4 17:32:55 UTC 2021



On January 4, 2021 3:28:48 PM UTC, Brian Goetz <brian.goetz at oracle.com> wrote:
>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?)

If you use pattern matching without inference, the mix between parenthesis and angle brackets rapidly becomes unreadable, so for a type pattern inside a switch, I think that even the diamond syntax is too much.

So IMO we should use the same inference as the method reference for the type pattern in a switch. 

>
>But if we can't do that, we can do the next best thing: allow diamond
>here:
>
>     if (m instanceof EnumMap<> em) { ... }

see my comment in a sibling thread.

Remi


-- 
Envoyé de mon appareil Android avec Courriel K-9 Mail. Veuillez excuser ma brièveté.


More information about the amber-spec-experts mailing list