1

I have and interface:

import java.util.Optional;

public interface SomeInterface<T> {
    Optional<Integer> someMethod();
}

Let us call a method of the interface instance:

public class CheckInterfaceInstance {
    public void check(SomeInterface<?> instance) {
        instance.someMethod().get().doubleValue();
    }
}

All is good, no compilation errors.

But if I declare the argument of the check() method without "any type" then we have a compilation error:

public class CheckInterfaceInstance {
    public void check(SomeInterface instance) {   //I removed <?>
        instance.someMethod().get().doubleValue();
    }
}

Compiler treats the type of instance.someMethod().get() as Object. So it complains about not existing method .doubleValue().

As you can see Optional<Integer> someMethod() declaration is not related to the <T> of SomeInterface at all. But the compiler misses the type of Optional.

Why?

Nikolas Charalambidis
  • 40,893
  • 16
  • 117
  • 183
trs
  • 19
  • 2
  • 2
    "As you can see Optional someMethod() declaration is not related to the of SomeInterface at all." Raw types don't work in this way. When you use raw types you lose the generic benefits for the current class. – davidxxx Apr 26 '19 at 11:56
  • `instance.someMethod().get()` returns `Object` because `instance.someMethod()` returns raw `Optional`. – Andy Turner Apr 26 '19 at 12:03
  • Found the answer here: https://stackoverflow.com/questions/27314649/why-does-javac-complain-about-generics-unrelated-to-the-class-type-arguments Thanks to all! – trs Apr 26 '19 at 12:13
  • @AndyTurner my bad, removed comment – Eugene Apr 26 '19 at 12:18

0 Answers0