9

We all know that Optional<T> has a method T get(), so why does it not implement Supplier<T>?

If there happens to be no reason why, would it break any previous code if Oracle were to implement it into a future version of Java?

Naman
  • 27,789
  • 26
  • 218
  • 353
Jacob G.
  • 28,856
  • 5
  • 62
  • 116
  • 4
    It raises a `NoSuchElementException` exception if it's empty; in its empty state it is not a `Supplier`. – teppic Oct 17 '17 at 04:33
  • 2
    You shouldn't use `Optional#get()` anyway, so it is actually a good thing it doesn't implement that interface. – Tom Oct 17 '17 at 04:34
  • @teppic But it's an unchecked exception, so what's the issue? – Jacob G. Oct 17 '17 at 04:35
  • 1
    Would you clarify "you shouldn't use..."? – Zhro Oct 17 '17 at 04:35
  • It's not a question of whether it could implement `Supplier`, but whether it should. I'd suggest that it would be hostile to clients to pass them a "Supplier" that might blow up. – teppic Oct 17 '17 at 04:37
  • 2
    @Zhro `Optional#get()` is unsafe and not better then the "usual" `null` check. Use other methods like `orElse(..)` instead. (further reading: https://dzone.com/articles/java-8-optional-replace-your-get-calls) – Tom Oct 17 '17 at 04:38
  • 1
    @Tom I made a new question to further query your suggestion. See https://stackoverflow.com/questions/46782731 – Zhro Oct 17 '17 at 04:57

3 Answers3

11

It's because they mean different things.

An Optional<T> is an argument that may or may not be provided, a return value that may or may not be provided, or a variable that may or may not be assigned a value. If it has a value, you can use .get() to retrieve it. .get() may throw an exception if you do something wrong, i.e., if you call it when the value is not present.

A Supplier<T> is a functional object that will provide a value (or null) on demand. Unlike an Optional<T>, it's reasonable for Supplier.get() to return a different value every time you call it. If Supplier.get() throws an exception, it means that something went wrong in its implementation, not that the caller made a mistake.

Matt Timmermans
  • 53,709
  • 3
  • 46
  • 87
2

As @MattTimmermans explains, there's no logical reason for Optional to implement Supplier. However, Java's method references make it very easy to convert between interfaces sharing the same functional signature. Given an Optional<T> o, you can pass it to any method or variable expecting a Supplier<T> in the form of o::get.

shmosel
  • 49,289
  • 6
  • 73
  • 138
2

None of interfaces in java.util.function package have implementing classes (at least Java platform classes). I think this is because these interfaces were not designed for any other purposes but, as package description says, to provide target types for lambda expressions and method references.

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275