3 ms·
Isn't map/flatMap and orElse enough, if only for Optional?
by dapz 13y ago
Isn't map/flatMap and orElse enough, if only for Optional?
- hrjet 13y agoIt's not enough for compactly expressing imperative logic. In Scala: 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.
- benjiweber 13y agoThere are several ways of doing it concisely with the Java Optional 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; } } }