Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why doesn't java.util.Optional implement Iterable?

Why doesn't Java 8's Optional implement Iterable?

I assume it's a deliberate language choice but I'm wondering why. Scala's Option and Haskell's Maybe implement traversal methods analogous to Iterable. FWIW, Java 9 will implement Optional.stream() (JDK-8050820).

like image 478
tariksbl Avatar asked Oct 13 '16 14:10

tariksbl


1 Answers

I'm not an expert on Scala or Haskell, but my belief is that those languages have constructs such as sequence comprehension that make it quite useful for Option or Maybe to be Traversable.

It may be that Java's Iterable is analogous to Traversable but the rest of the Java language doesn't provide very much support around it. The only thing Iterable does in Java is enable its use in an enhanced-for ("for each") loop. Consider for example if Java's Optional were to implement Iterable. That would allow an Optional to be used like this:

Optional<T> opt = ... ;
for (T t : opt) {
    doSomethingWith(t);
}

It's kind of misleading to write this as a loop, since it executes zero or one times. To be less misleading, one might as well write this:

if (opt.isPresent()) {
    doSomethingWith(opt.get());
}

or preferably

opt.ifPresent(this::doSomething);

I don't know for a fact the reason that Optional was not made Iterable. The Java 8 lambda expert group had several face-to-face meetings where a bunch of things were probably discussed and never written down. I can easily imagine this topic being raised at such a meeting, and dismissed as not being very useful, given the existence of much more useful alternatives such as ifPresent.

like image 174
Stuart Marks Avatar answered Oct 30 '22 10:10

Stuart Marks