Java 编译因方法引用而失败,但适用于 lambda
Java compilation fail with method reference but works with lambda
我们正在尝试将重载的 collect
方法添加到我们当前定义为的扩展 Java 流 API 中:
interface ExtendedStream<R> extends Stream<R> {
<R1> R1 collect(SerializableSupplier<Collector<? super R, ?, R1>> supplier);
}
SerializableSupplier
定义为:
interface SerializableSupplier<T> extends Serializable, Supplier<T> {
}
使用 lambda 调用此 collect 方法工作正常,但使用方法引用调用它无法编译并出现错误,例如:
Error:(50, 72) java: incompatible types: cannot infer type-variable(s) R1,capture#1 of ?,T
(argument mismatch; bad return type in method reference
java.util.stream.Collector<T,capture#1 of ?,java.util.List<T>> cannot be converted to java.util.stream.Collector<? super java.util.Map.Entry<java.lang.Integer,java.lang.String>,?,R1>)
我创建了一个独立的 Java class here,您可以将其加载到编译器中进行试用。
我目前使用的是Java版本:
java version "1.8.0_144"
Java(TM) SE Runtime Environment (build 1.8.0_144-b01)
Java HotSpot(TM) 64-Bit Server VM (build 25.144-b01, mixed mode)
这是错误还是我们定义事物的方式有误?
注意:我从 IntelliJ 和使用 Maven 编译时都遇到了这个编译错误。我不使用 Eclipse。
干杯,
高尔德
这是 javac 8
中的一个错误,因为它与 javac-9
(最新版本)编译得很好 - 我只是找不到它,我真的真的试过了至.
几乎像往常一样添加更多类型信息可以解决这些问题...另请注意,我已将您的 Comparator
更改为 Comparator.comparingInt...
:
return entrySet.stream().sorted(
Comparator.comparingInt(Entry::getKey)).collect(
Collectors::<Map.Entry<Integer, String>> toList);
我们正在尝试将重载的 collect
方法添加到我们当前定义为的扩展 Java 流 API 中:
interface ExtendedStream<R> extends Stream<R> {
<R1> R1 collect(SerializableSupplier<Collector<? super R, ?, R1>> supplier);
}
SerializableSupplier
定义为:
interface SerializableSupplier<T> extends Serializable, Supplier<T> {
}
使用 lambda 调用此 collect 方法工作正常,但使用方法引用调用它无法编译并出现错误,例如:
Error:(50, 72) java: incompatible types: cannot infer type-variable(s) R1,capture#1 of ?,T
(argument mismatch; bad return type in method reference
java.util.stream.Collector<T,capture#1 of ?,java.util.List<T>> cannot be converted to java.util.stream.Collector<? super java.util.Map.Entry<java.lang.Integer,java.lang.String>,?,R1>)
我创建了一个独立的 Java class here,您可以将其加载到编译器中进行试用。
我目前使用的是Java版本:
java version "1.8.0_144"
Java(TM) SE Runtime Environment (build 1.8.0_144-b01)
Java HotSpot(TM) 64-Bit Server VM (build 25.144-b01, mixed mode)
这是错误还是我们定义事物的方式有误?
注意:我从 IntelliJ 和使用 Maven 编译时都遇到了这个编译错误。我不使用 Eclipse。
干杯, 高尔德
这是 javac 8
中的一个错误,因为它与 javac-9
(最新版本)编译得很好 - 我只是找不到它,我真的真的试过了至.
几乎像往常一样添加更多类型信息可以解决这些问题...另请注意,我已将您的 Comparator
更改为 Comparator.comparingInt...
:
return entrySet.stream().sorted(
Comparator.comparingInt(Entry::getKey)).collect(
Collectors::<Map.Entry<Integer, String>> toList);