Note that static cast could be implemented as a library method! public class ensure { static <T> T type(T t) { return t; } }
switch(ensure.<Number>type(o.get1().get2())) { ... } This is exactly a compile-time check :-) With best regards, Tagir Valeev. On Tue, Jul 28, 2020 at 4:29 AM Brian Goetz <brian.go...@oracle.com> wrote: > > > > 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”. > > > Alternately, what is too bad is that there _is_ such a thing as a "static > cast", but it uses the same syntax, and has the same sort of contextual > problem that Jens has complained about here! > > Suppose we have: > > class Foo<T> { > void m(Foo f) { > Foo<String> fs = (Foo<String>) f; // static cast! > } > } > > The cast to `Foo<String>` is purely a static cast. (Same with casts to > things like `Foo<T>` or `T[]` or `T`.) Essentially, if the cast type is not > reifiable, but the two types are cast-convertible (perhaps with an unchecked > warning), then its a static type, otherwise its a dynamic type. This fact > has cause plenty of trouble in Valhalla, since having such a cast magically > become a dynamic one would surely cause problems. > > But, yes, if casts could be explicitly denoted as static or dynamic, this > would do the trick. > > 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). > > > ... and we said the same thing the last time we were at this crossroads, with > respect to totality in statement switches. Indeed, when the switch > rehabiliation is complete, we can go back and ask what additional optional > type checking we want to perform. > > The mistake of declaring variables as `T t` rather than `t : T` (where you > can elide the type ascription in some cases) haunts us ever day ... if we had > gone this way, you could get what you want quite naturally with > > switch (x : T) { ... } > > as a static type assertion.