How to upcast object contained in Java 8 Optional?

Viewed 12558

Is there an efficient way to perform upcasting while using an Optional object. Here is a sample code:

class A{}
class B extends A{}

B func(){
    //do something
    return new B();
}

Optional<B> func2(){
    //do something
    return Optional.of(new B());
}

main() {
    A a = func(); // Upcasting works fine
    B b = func(); // Upcasting works fine
    Optional<B> b = func2(); // 1. Works fine
    Optional<A> a = func2(); // 2. How to make this work ?
}

(2.) gives an error. I can solve it by creating another function.

But is there an efficient way, so that func2() can be used for both (1.) and (2.) ?

4 Answers

The cleanest way to do this I think would be Optional<A> a = func2().flatMap(Optional::of) or Optional<A> a = func2().map(Function.identity()) because both do not require casting and only use existing functionality.

Related