if (!(x instanceof String y)) syntax - better syntax?

Brian Goetz brian.goetz at oracle.com
Fri Feb 7 16:02:55 UTC 2020


> I'm not sure if now is an appropriate time (or how one should bring up
> something like this)

Heh, it's never a good time, and there's never a good way, but you came 
about as close as is possible!

> I noticed a bit of friction in regards to this
> particular style of code:
>
>      if (!(x instanceof String y)) return;
>      // carry on, with y available of type Strin.

Indeed, it is definitely an "idiom" that may take a little getting used to.

> Given that a new language feature is being introduced which is catering
> rather explicitly to this particular 'if not an instance of, then' style,
> is there room to add a small, entirely backwards compatible syntax feature
> [1]?
>
> Something like:
>
>      if (x !instanceof String y) return;

Not a terrible idea!  Something worth considering.

> I'm not sure if it would be appropriate to debate here if this should be
> tagged onto the aims for e.g. JDK15's expanded instanceof support (
> Preview-2 [2] ), or if this should be its own proposal, or if this is even
> the appropriate channel for such ideas.

My inclination is not to load down pattern matching with this, and give 
us time to gather evidence about how much of a friction point it is.

> [1] I'm jumping the gun a little bit on how backwards compatible this is. I
> _think_ so, as it's a straight up syntax error right now, but before I
> write a PoC patch to javac, I thought I'd check if the idea itself is sound
> before delving that deep.

The claim that it is a simple rewriting and introduces no ambiguities is 
credible; would have to be verified.




More information about the amber-dev mailing list