2
\$\begingroup\$

My method getProjectDir() will return an Optional which contains the path to the project directory, or an empty container:

Optional<Path> getProjectDir() { ... }

I have another method, getSrcDir() which depends on getProjectDir():

Optional<Path> getSrcDir() {
    Optional<Path> projectDir = getProjectDir();
    if (projectDir.isPresent()) {
        return Optional.of(projectDir.get().resolve("src"));
    }

    return Optional.empty();        
}

Everything works, but I feel the if statement is clunky. Is there any single statement which says "If the project dir exists, append "/src" to it, else return an empty optional. Please let me know if and how it can be done.

\$\endgroup\$
3
\$\begingroup\$

Sure there is! You're looking for Optional.map

If a value is present, apply the provided mapping function to it, and if the result is non-null, return an Optional describing the result. Otherwise return an empty Optional.

Optional<Path> getSrcDir() {
    return getProjectDir().map(p -> p.resolve("src"));
}
\$\endgroup\$
1
  • \$\begingroup\$ This is as beautiful as it should be. \$\endgroup\$ – Hai Vu Jan 22 '18 at 2:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.