Hacker News new | past | comments | ask | show | jobs | submit login

Yeah, I hope I am interpreting this the wrong the way. But instead of doing

  X.getA().getB().getC().getD()
we have to

   X.flatMap(X::getA)
    .flatMap(X::getB)
    .map(X::getC)
    .orElse("UNKNOWN");  //[1]
Not sure why this is going to be better?

[1] http://www.oracle.com/technetwork/articles/java/java8-option...




That's not a fair comparison, as the flatMaps are eating nulls (really Optional.empty()s) while the naked calls will throw NPEs. The equivalent code for the first case is:

  String result = "UNKNOWN";
  T a = X.getA();
  if (a != null) {
    T b = a.getB();
    if (b != null) {
      String c = b.getC();
      if (c != null) {
        result = c;
      }
    }
  }
Optional (like Scala's Option or Haskell's Maybe) are useful because they force you to reason about "empty" cases. Whereas in typical java code there is no way for the compiler to force to you handle the possibility of nulls (thus leading to NPEs), Wrapping a type in Optional forces you to deal with the case where the result is not present, leading to more correct programs. Plus, it gives you handy tools for dealing with non-present values, like allowing a chain of computation--any step of which may fail--without needing failure checks on every step.




Join us for AI Startup School this June 16-17 in San Francisco!

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: