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);
}
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, 2022Comments
-
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 anOptional<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?