Patterns for arrays of specific length
Remi Forax
forax at univ-mlv.fr
Mon Mar 4 08:08:47 UTC 2019
Hi Tagir,
----- Mail original -----
> De: "Tagir Valeev" <amaembo at gmail.com>
> À: "amber-spec-experts" <amber-spec-experts at openjdk.java.net>
> Envoyé: Lundi 4 Mars 2019 04:30:09
> Objet: Patterns for arrays of specific length
> Hello!
>
> In intellij IDEA code we often see snippets like this:
>
> final ResolveResult[] resolveResults = multiResolve(false);
> return resolveResults.length == 1 && resolveResults[0].isValidResult() ?
> resolveResults[0].getElement() : null;
Arrays.stream(resolveResults).findFirst().filter(ResolveResult::isValidResult).map(ResolveResult::getElement).orElse(null)
and obviously, the method should return an Optional instead of calling orElse(null) at the end.
Rémi
>
> I wonder if special kind of patterns to cover such case could be invented like
>
> return multiResolve(false) instanceof ResolveResult[] {var res} &&
> res.isValidResult() ?
> res.getElement() : null;
>
> In essence it should be a deconstruction pattern for arrays. I don't
> remember whether it was discussed, but probably I'm missing something.
>
> Alternatively this could be covered by utility method like
>
> static <T> T getOnlyElement(T[] array) {
> return array.length == 1 ? array[0] : null;
> }
>
> return getOnlyElement(multiResolve(false)) instanceof ResolveResult
> res && res.isValidResult() ?
> res.getElement() : null;
>
> But this doesn't scale for arrays of bigger length.
>
> With best regards,
> Tagir Valeev.
More information about the amber-spec-experts
mailing list