Hacker Newsnew | comments | show | ask | jobs | submit login

It'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.



There 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;
          }
      }
  }

-----




Guidelines | FAQ | Support | API | Lists | Bookmarklet | DMCA | Y Combinator | Apply | Contact

Search: