Let\'s say I have two classes and two methods:
class Scratch {
private class A{}
private class B extends A{}
public Optional getItems(List&
An Optional
is not a sub-class of Optional
.
In the first case, you have a Stream
, so findFirst
returns an Optional
, which cannot be converted to an Optional
.
In the second case, you have a stream pipeline that returns an instance of B
. When you pass that instance to Optional.of()
, the compiler sees that the return type of the method is Optional
, so Optional.of()
returns an Optional
(since an Optional
can hold an instance of B
as its value (since B
extends A
)).