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

Brian Goetz brian.goetz at oracle.com
Tue Jan 25 19:49:12 UTC 2022

> 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 AerrayList 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.)  

More information about the amber-spec-experts mailing list