Observation about nulls in type patterns
Remi Forax
forax at univ-mlv.fr
Mon Jul 27 21:05:22 UTC 2020
> De: "Guy Steele" <guy.steele at oracle.com>
> À: "Brian Goetz" <brian.goetz at oracle.com>
> Cc: "amber-spec-experts" <amber-spec-experts at openjdk.java.net>
> Envoyé: Lundi 27 Juillet 2020 22:38:38
> Objet: Re: Observation about nulls in type patterns
>> On Jul 27, 2020, at 4:25 PM, Brian Goetz < [ mailto:brian.goetz at oracle.com |
>> 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?
Instead of having an idiom, we can use a restricted Java-ish syntax.
For me it's a lot like when you want a serializable lambda and you end up with an ad hoc java-ish syntax (Foo & Serializable) s -> ...
So i propose Number | null,
switch (o.get1().get2()) {
case Integer i -> ...
case Number | null n -> …
}
it's a restricted syntax too, it's either "type | null" and it's obviously explicit, it also makes the rule that say if a switch accept null or not more obvious because it's decouple from the notion of a total coverage, if a case accept null then the switch accept null.
> —Guy
Rémi
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://mail.openjdk.java.net/pipermail/amber-spec-experts/attachments/20200727/e08f4607/attachment-0001.htm>
More information about the amber-spec-experts
mailing list