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> {
}
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With