内联代码-不兼容的类型:无法推断类型变量T

时间:2019-02-13 11:08:34

标签: java

我有这样的一段代码:

this.events2 = events

我自然想做的是:

 Stream<Supplier<String>> stream = Stream.of(() -> "str");
 stream.map(Supplier::get).findFirst();

但是我得到了

  

不兼容的类型:无法推断类型变量T

  

无效的方法引用非静态方法get()无法被引用   从静态上下文中

我很困惑,因为我认为内联代码不会改变它的行为。 内联后出现错误的机制是什么?

编辑: 决定添加一些评论以强调我的想法。让我们来简化代码,例如:

Stream.of(() -> "str").map(Supplier::get).findFirst();

我可以做到:

Stream<Integer> stream = Stream.of(1, 2);
stream.of(1, 2).map(i -> i * i).findFirst();

没关系,那么为什么上面的示例(不起作用)?

1 个答案:

答案 0 :(得分:2)

在我的情况下,该行:

Stream.of(() -> "str").map(Supplier::get).findFirst();

给我编译错误"The method of(() -> {}) is undefined for the type Stream"。由于无法推断类型,因此会产生编译错误。但是,当您使用Stream<Supplier<String>> stream = Stream.of(() -> "str");时,它将自动从引用变量清除中推断出类型。有关通用类型推断的更多信息,请link

Stream.<Supplier<String>>of(() -> "str").map(Supplier::get).findFirst();

将按预期工作。