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?
Casting the value of an Optional or the elements of a Stream is a two-step-process: First we have to filter out instances of the wrong type, then we can cast to the desired one. With the methods on Class , we do this with method references. Using the example of Optional : Optional<?>
In SPL, an optional type is used when a variable or attribute might have no data value associated with it because the value is unavailable or unknown.
Optional Class | isPresent() function The isPresent() function in Optional Class is used to evaluate whether the value if assigned to variable is present or not. Syntax value.isPresent() Returns: It returns true if value is assigned otherwise false.
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);
}
Return a Optional<? extends Inter>
instead of an Optional<Inter>
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With