Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting type inside Optional

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?

like image 402
sprinter Avatar asked Dec 04 '17 12:12

sprinter


People also ask

How do you type Optional in Java?

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<?>

What is an Optional data type?

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.

What is isPresent in Optional?

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.


2 Answers

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);
}
like image 113
Christian Avatar answered Oct 17 '22 00:10

Christian


Return a Optional<? extends Inter> instead of an Optional<Inter>.

like image 2
sprinter Avatar answered Oct 17 '22 00:10

sprinter