Why does the <T> option not implement the <T> Provider?

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

If there is no reason, would any previous code violate if Oracle introduced it in a future version of Java?

+5
source share
3 answers

This is 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 matters, you can use .get() to get it. .get() can throw an exception if something is wrong, i.e. if you call it when this value is missing.

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

+7
source

As @MattTimmermans explains , there is no logical reason for Optional to implement a Supplier . However, Java method references simplify conversions between interfaces that use the same functional signature. Given Optional<T> o , you can pass it to any method or variable that expects Supplier<T> in the form o::get .

+2
source

None of the interfaces in the java.util.function package implement classes (at least Java platform classes). I think this is due to the fact that these interfaces were not intended for any other purposes, but, as stated in the package description, to provide target types for lambda expressions and method references.

+2
source

Source: https://habr.com/ru/post/1272679/


All Articles