> On Jul 27, 2020, at 4:57 PM, Brian Goetz <[email protected]> wrote: > > > >> In the text above quoted from Jens Lideström, is some text missing in the >> third line? > > I forwarded the complete mail, but perhaps his thoughts were incomplete.... > >> >> 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? >> > > It could, and this would work when your brain-analysis was correct, but would > otherwise hide errors. The result of get2() has a dynamic type D, and a > static type S. If we cast to Number, we're asserting that D <: Number; if > this is not true, then we'll get a CCE at runtime. For code that is > control-flow dominated by the test, program analysis is free to conclude the > test succeeded (otherwise we'd not be executing that code), so we can > conclude that, if it ever runs, the last pattern is total and the compiler > can elide the dynamic test. > > But this has the drawback that we might be wrong about what `get2()` returns, > and then it would CCE; presumably we are using type patterns in switch to > _avoid_ CCEs. If `get2` returns Object, and might return something that is > not a subtype of Number, the compiler won't balk (Object is cast-convertible > to Number), but we'll get a runtime error. > > What we really want to do is assert that the _static_ return type of `get2()` > is a subtype of Number. And for that, the language provides the obvious way > to do that already: > > Number n = o.get1().get2() > switch (n) { … }
Indeed; but it is unfortunate that it requires a separate statement (actually, a declaration), so is relatively unsuitable for use with switch expressions. Too bad there isn’t such a thing as a “static cast”. (Oooh! Ooh! “(static <type>) <expression>” ! :-). No, don’t do that; it’s a terrible pun on the word “static”. But if this turns out to be a big problem, it does suggest that one could have a form of switch in which the static type of the switch expression is declared. I don’t suggest pursuing it now, but it’s one idea to keep in our back pocket (where we can firmly sit on it unless and until needed).
