Should we allow the diamond syntax in a cast ? If the answer is yes, then it should be allowed in type patterns.
regards, Remi On January 4, 2021 3:28:48 PM UTC, Brian Goetz <brian.go...@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?) > >But if we can't do that, we can do the next best thing: allow diamond >here: > > if (m instanceof EnumMap<> em) { ... } -- Envoyé de mon appareil Android avec Courriel K-9 Mail. Veuillez excuser ma brièveté.