Search code examples
haskelljava-8option-type

Boolean Predicate (guard) in Java Optional


Here's the method I have.

public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context) {
    if (isInRoutesFile(element)) {
        return controllerName(element)
                .flatMap(name -> findController(element.getProject(), name))
                .map(controller -> new PsiReference[]{new RPsiElementReference(controller)})
                .orElse(new PsiReference[0]);
    }

    return new PsiReference[0];
}

Now, I'd like to avoid the if clause and somehow built the predicate into the Optional chain in order to not duplicate new PsiReference[0].

For comparison, Haskell has a function guard for exactly that purpose. Here's how it would look like;

references :: Element -> Maybe [Reference]
references element = do
    guard $ isInRoutesFile element
    controllerName element >>= findController (getProject element) >>= Just . return . Reference

This code will return Nothing, which is equivalent to Optional.empty() in case isInRoutesFile element is False. What's the Java way to have a guard?


Solution

  • It's filter.

    return Optional.of(element)
             .filter(this::isInRoutesFile)
             .flatMap(this::controllerName)
             .flatMap(name -> findController(element.getProjcet(), name))
             ...;