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?
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.
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
.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With