Observation about nulls in type patterns

Guy Steele guy.steele at oracle.com
Mon Jul 27 20:38:38 UTC 2020

> On Jul 27, 2020, at 4:25 PM, Brian Goetz <brian.goetz at oracle.com> wrote:
> ...
> If get2 is some method that is declared to return Number then the second
> pattern is total and will accept null; if get2 is declared to return
> Object pattern the IS total and WILL accept null.

In the text above quoted from Jens Lideström, is some text missing in the third line?

Returning to an earlier part of your message:

> Of course, if you want to make it more obvious, you can write more explicit code.  You can, for example, refactor
> switch (o.get1().get2()) {
>     case Integer i: ...
>     case Number n: ...
> }
> into
> Number t = o.get1().get2();
> switch (t) {
>     case Integer i: ...
>     case Number n: ...
> }
> and now it is more obvious again.  

Presumably that latter could also be written as

switch ((Number)(o.get1().get2())) {
    case Integer i: ...
    case Number n: …

and it might become a popular idiom always to provide that explicit cast in switch statements, and especially switch expressions, when there might be any doubt as to whether the switch has total coverage?


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.java.net/pipermail/amber-spec-experts/attachments/20200727/6dff0ff5/attachment.htm>

More information about the amber-spec-experts mailing list