Stream.findFirst different than Optional.of?

  • A+

Lets say I have two classes and two methods:

class Scratch {     private class A{}     private class B extends A{}      public Optional<A> getItems(List<String> items){         return              .map(s -> new B())              .findFirst();     }      public Optional<A> getItems2(List<String> items){         return Optional.of(                     .map(s -> new B())                  .findFirst()                  .get()         );     } } 

Why does getItems2 compile while getItems gives compiler error

incompatible types: java.util.Optional<Scratch.B> cannot be converted to java.util.Optional<Scratch.A> 

So when I get the value of the Optional returned by findFirst and wrap it again with Optional.of the compiler recognizes the inheritance but not if I use directly the result of findFirst.


The issue you have is with inheritance for generics. Optional< B > doesn't extend Optional< A >, so it can't be returned as such.

I'd imagine that something like this:

public Optional<? extends A> getItems( List<String> items){     return         .map(s -> new B())         .findFirst(); } 


public Optional<?> getItems( List<String> items){     return         .map(s -> new B())         .findFirst(); } 

Would work fine, depending on your needs.

Edit: escaping some characters


:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: