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

Reinier Zwitserloot reinier at zwitserloot.com
Fri Feb 7 00:53:06 UTC 2020


I'm not sure if now is an appropriate time (or how one should bring up
something like this), but 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.

This is a stated goal of why the instanceof patternmatch feature's rules on
where the declared 'y' variable is available ('binding variables') works as
it does.

That's great; we've debated it at length before.

However, the syntax of this particular construct is a bit unfortunate; I
see newbies write if (!x instanceof String) or if (x !instanceof String)
relatively often; the second one gives a straight up syntax error, but the
first is a bit more convoluted ('x is not boolean'). Even disregarding the
anecdotal evidence that those new to java fairly consistently misjudge how
to do an if-not-an-instance-of check, the correct syntax is rather
unwieldy. Maybe it's comfortable to any LISP fans in the audience, but it's
a few too many parentheses for my tastes.

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;

Any form of the *ReferenceType* AST node accepts this form, so also the
older form:

    boolean z = x !instanceof String; // valid. equivalent to z = !(x
instanceof String).

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.

[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.
[2] https://bugs.openjdk.java.net/browse/JDK-8235186


 --Reinier Zwitserloot


More information about the amber-dev mailing list