Diamond in type patterns?

Remi Forax forax at univ-mlv.fr
Mon Feb 1 16:19:47 UTC 2021


Hi Brian, 
Thinking a little bit more on this, 
i've discovered that the inference you are proposing for a type pattern doesn't work exactly like the inference works in the rest of the language. 

With just a simple example, 
Object o = ... 
if (o instanceof List<> list) { ... } 

Given that there is no type information that can be extracted from the type of 'o', the usual inference will infer List<Object> so the code will not compile. What should be inferred is List<?> but this means having a different inference mechanism :( 

regards, 
Rémi 

> De: "Brian Goetz" <brian.goetz at oracle.com>
> À: "amber-spec-experts" <amber-spec-experts at openjdk.java.net>
> Envoyé: Lundi 4 Janvier 2021 16:28:48
> Objet: Diamond in type patterns?

> 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/20210201/641c9560/attachment-0001.htm>


More information about the amber-spec-experts mailing list