Patterns for arrays of specific length

Tagir Valeev amaembo at
Mon Mar 4 03:30:09 UTC 2019


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;

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-observers mailing list