Max Smirnov
Max Smirnov

Reputation: 603

Implicit interface implementation

I have the following MyOpt interface:

public interface MyOpt<T> {
    T get();
    boolean isPresent();
}

And the class method, that returns one of MyOpt implementations:

private MyOpt<String> read() { ... }

At the same time, Optional has the same methods and signatures and can be MyOpt subtype. But when refactor class method to return Optional like this:

private <X extends MyOpt<String>> X read() {
    Optional<String> empty = Optional.empty();
    return empty;
}

IntelliJ shows this error:

Required type: X

Provided: Optional<java.lang.String>

How can I use Optional as an implementation of MyOpt?

Upvotes: 0

Views: 130

Answers (1)

Louis Wasserman
Louis Wasserman

Reputation: 198103

How can I use Optional as an implementation of MyOpt?

You cannot.

Optional is a final class defined in the JDK. Just because you share the same method names and types, does not mean you can treat your class as related to Optional in any way.

Upvotes: 1

Related Questions