Casting type inside Optional

13,509

Solution 1

To make clear that you only need casting, you can use Class::cast with .map:

class Foo implements Inter {
    void doSomething();
}

Optional<Inter> getPossible() {
    Optional<Foo> possible = ...;
    possible.ifPresent(Foo::doSomething);
    return possible.map(Inter.class::cast);
}

Solution 2

One alternative would be to edit the method signature in Foo to become the following:

class Foo implements Inter {
    Inter doSomething() {
        ...
        return this;
    }
}

Now, you can simplify getPossible to the following:

Optional<Inter> getPossible() {
    Optional<Foo> possible = ...;
    return possible.map(Foo::doSomething);
}
Share:
13,509
sprinter
Author by

sprinter

While I work in IT coding is a hobby for me. Mostly Java but some Haskell and Swift. My passions are clean coding and test driven development.

Updated on July 20, 2022

Comments

  • sprinter
    sprinter almost 2 years

    I have the following:

    class Foo implements Inter {
        void doSomething();
    }
    
    Optional<Inter> getPossible() {
        Optional<Foo> possible = ...;
        possible.ifPresent(Foo::doSomething);
        return possible.map(f -> f);
    }
    

    getPossible needs to return an Optional<Inter> because it's overriding a superclass's implementation.

    That map at the end of the method is purely to convert the type. Is there a more elegant option?