Diamond in type patterns (was: Reviewing feedback on patterns in switch)

Remi Forax forax at univ-mlv.fr
Tue Jan 25 22:01:11 UTC 2022

----- Original Message -----
> From: "Brian Goetz" <brian.goetz at oracle.com>
> To: "amber-spec-experts" <amber-spec-experts at openjdk.java.net>
> Sent: Tuesday, January 25, 2022 8:49:12 PM
> Subject: Diamond in type patterns (was: Reviewing feedback on patterns in switch)

>> 4.  Diamond for type patterns (and record patterns)
> The type pattern `T t` declares `t`, if the pattern matches, with the type T.
> If T is a generic type, then we do a consistency check to ensure soundness:
>    List<String> list = …
>    switch (list) {
>        case ArrayList<String> a: A  // ok
>        case ArrayList<?> a: B   // ok
>        case ArrayList a: C    // ok, raw type
>        case ArrayList<Frog> a:  // error, would require unchecked conversion
>   }
> All of these make sense, but users are going to be tempted to use `case
> ArrayList a` rather than the full `case ArrayList<String> a`, and then be sad
> (or confused) when they get type errors.  Since the type can be precisely
> defined by inference, this seems a place for allowing diamond:
>    case ArrayList<> a: B
> (And the same when we have record patterns.)

The questions we did not answer the last time we talk about that subject
 - why should we allow raw types here ?
 - given that this is equivalent to an instanceof + cast, why we can not use diamond inference on cast ?
 - how this inference work ? Is is the same inference than with the diamond constructor ?
   By example, if we have

   List<?> list = ...
   switch(list) {
     case ArrayList<> a:

   Do we really want to infer ArrayList<Object> to then rejects it because it's an unsafe cast.


More information about the amber-spec-experts mailing list