The type required is the same as the type found.

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 two lines in one line, such as:

 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.

Requires: Foo.Bar

Found: Foo.Bar

Why is this?

 public class Foo<T> { public class Bar extends SomeOtherClass<T> { public void doSomething(T t) { } } } 

And the last class:

 public class SomeOtherClass<T> { } 
+5
source share
2 answers

There are several scenarios in which Java cannot fully handle type inference (which, in his opinion, should). This is one of these scenarios.

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

 Foo<String>.Bar fooBar2 = new Foo<String>().new Bar(); 
+6
source

In the first example, you tell java that you are using Foo<string> , declaring foo as Foo<string> :

 Foo<String> foo = new Foo<>(); 

You need to clarify the type of the template in foo better in the second example:

 Foo<String>.Bar fooBar2 = (new Foo<String>()).new Bar(); 
0
source

All Articles