所需类型与找到的类型相同 [英] Required type is same as found type

查看:28
本文介绍了所需类型与找到的类型相同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这样做:

    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:

不兼容的类型.

必需:Foo.Bar

找到:Foo.Bar

这是为什么?

public class Foo<T> {


    public class Bar extends SomeOtherClass<T> {

        public void doSomething(T t) {

        }

    }

}

最后一节课:

public class SomeOtherClass<T> {
}

推荐答案

在某些情况下,Java 无法很好地处理类型推断(当人们认为应该这样做时).这是其中一种情况.

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.

如果您显式地将类型传递给 new 调用,它将编译:

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

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

这篇关于所需类型与找到的类型相同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆