by hibikir · 12y ago · 0 comments
optionalF.map( _.whatever ).getOrElse(fallback)
or perhaps (optionalF <+> optionalFallback).getOrElse(finalFallback)
For those unfamiliar with <+>, see here: http://www.chrisstucchio.com/blog/2014/handle_failure_with_p... optional match {
case Some(x) => whatever(x)
case None => fallback
}
Second, I find the pattern matching code much clearer. Sure, it's also longer, but clarity trumps everything. resultOption match {
case Some(x) => println(x)
case None => println("error")
}
Without pattern match: if (resultOption.isDefined) {
println(resultOption.get)
} else {
println("Error")
}
The .get is the problem. import java.util.Optional;
public class Scratch {
public static void main(String... args) {
Optional<String> foo = Optional.of("foo");
Optional<String> bar = Optional.empty();
System.out.println(foo.orElse("Error"));
System.out.println(bar.orElse("Error"));
foo.map(Print::print).orElseGet(() -> Print.print("Error"));
bar.map(Print::print).orElseGet(() -> Print.print("Error"));
foo.ifPresent(Print::print);
}
static class Print {
public static <T> T print(T val) {
System.out.println(val);
return val;
}
}
}