Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Optional<T> not implement Supplier<T>?

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?

like image 722
Jacob G. Avatar asked Oct 17 '17 04:10

Jacob G.


3 Answers

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.

like image 199
Matt Timmermans Avatar answered Oct 13 '22 07:10

Matt Timmermans


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.

like image 37
shmosel Avatar answered Oct 13 '22 06:10

shmosel


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.

like image 2
Evgeniy Dorofeev Avatar answered Oct 13 '22 07:10

Evgeniy Dorofeev