Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Required type is same as found type

Tags:

java

types

I want to do this:

    Foo<String> foo = new Foo<>();
    Foo<String>.Bar fooBar = foo.new Bar();

    fooBar.doSomething("this works!");

But then the first 2 lines in a single line like:

Foo<String>.Bar fooBar2 = new Foo<>().new Bar();
fooBar2.doSomething("The above line gives: incompatible types. Required: Foo.Bar Found: Foo.Bar");

But the first line fails. I get:

incompatible types.

Required: Foo.Bar

Found: Foo.Bar

Why is that?

public class Foo<T> {


    public class Bar extends SomeOtherClass<T> {

        public void doSomething(T t) {

        }

    }

}

And the last class:

public class SomeOtherClass<T> {
}
like image 768
clankill3r Avatar asked Jun 04 '15 21:06

clankill3r


1 Answers

There are some scenarios in which Java can't handle the type inference all that well (when one thinks it should). This is one of those scenarios.

If you explicitly pass the type to the new invocation, it will compile:

Foo<String>.Bar fooBar2 = new Foo<String>().new Bar();
like image 181
Makoto Avatar answered Oct 13 '22 16:10

Makoto