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

Jesper Steen Møller jesper at selskabet.org
Fri Feb 7 22:14:50 UTC 2020


Additionally, javac could consider giving better help for "if (!obj instanceof SomeClass ..." since it will always be a typo, requiring parenthesis (as instanceof will never autobox a boolean).

Alternatively, we can leave it to IDEs to hint.

-Jesper

> On 7 Feb 2020, at 23.11, Remi Forax <forax at univ-mlv.fr> wrote:
> 
> One problem i see is that this idiom is currently popular because until 14 most of the time you had to do a cast and store the result in a local variable after the instanceof,
> now that we can do an instanceof and create a local variable with one expression, i'm not sure this idiom will be used a lot anymore,
> 
> I think that Tagir (correct me if i'm wrong) has already said that IntelliJ is/will be able to refactor this idiom to
>  return x instanceof String s && ...
> 
> Rémi
> 
> ----- Mail original -----
>> De: "Brian Goetz" <brian.goetz at oracle.com>
>> À: "Reinier Zwitserloot" <reinier at zwitserloot.com>, "amber-dev" <amber-dev at openjdk.java.net>
>> Envoyé: Vendredi 7 Février 2020 17:02:55
>> Objet: Re: if (!(x instanceof String y)) syntax - better syntax?
> 
>>> 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