Jacob G.
Jacob G.

Reputation: 29720

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?

Upvotes: 10

Views: 3693

Answers (3)

Evgeniy Dorofeev
Evgeniy Dorofeev

Reputation: 136082

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.

Upvotes: 2

shmosel
shmosel

Reputation: 50746

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.

Upvotes: 2

Matt Timmermans
Matt Timmermans

Reputation: 59303

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.

Upvotes: 13

Related Questions