vendredi 30 juin 2017

How to upcast Java 8 Optional objects?

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. Upcasting works fine
    Optional<A> a = func2(); // 2. Upcasting would not 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.) ?

Aucun commentaire:

Enregistrer un commentaire