英文:
Getting compile time error Inference variable T has incompatible bounds
问题
class CollectorUtils {
private CollectorUtils() {
}
public static <T> Collector<T, ?, T> onlyElement() {
return Collectors.collectingAndThen(Collectors.toList(), Iterables::getOnlyElement);
}
public static <T> Collector<T, ?, Optional<T>> optionalElement() {
return Collectors.collectingAndThen(Collectors.toList(), (list) -> {
return Optional.ofNullable(Iterables.getOnlyElement(list, (Object)null));
});
}
public static <T> Collector<T, ?, List<T>> toList() {
return Collectors.toCollection(ArrayList::new);
}
}
英文:
class CollectorUtils {
private CollectorUtils() {
}
public static <T> Collector<T, ?, T> onlyElement() {
return Collectors.collectingAndThen(Collectors.toList(), Iterables::getOnlyElement);
}
public static <T> Collector<T, ?, Optional<T>> optionalElement() {
return Collectors.collectingAndThen(Collectors.toList(), (list) -> {
return Optional.ofNullable(Iterables.getOnlyElement(list, (Object)null));
});
}
public static <T> Collector<T, ?, List<T>> toList() {
return Collectors.toCollection(ArrayList::new);
}
}
I am getting inference variable T has incompatible bounds.
java: incompatible types: inference variable T has incompatible bounds
equality constraints: T
lower bounds: T,java.lang.Object,T
答案1
得分: 3
注意: 在这个回答中,我只考虑编译错误。我不讨论问题中的代码是否是最佳的可能代码。
我假设 Iterables.getOnlyElement
是来自 Guava 库。
问题出在这一行:
return Optional.ofNullable(Iterables.getOnlyElement(list, (Object) null));
而应该将 null
转换为 T
,这样编译器可以安全地推断所有类型:
return Optional.ofNullable(Iterables.getOnlyElement(list, (T) null));
另外,你可以简化你的代码:
return Collectors.collectingAndThen(Collectors.toList(),
list -> Optional.ofNullable(Iterables.getOnlyElement(list, (T) null)));
英文:
NOTE: In this answer I'm only considering the compilation error. I'm not discussing whether the code of the question is the best possible one or not.
I assume Iterables.getOnlyElement
is from Guava.
The problem is with this line:
return Optional.ofNullable(Iterables.getOnlyElement(list, (Object) null));
Instead, cast null
to T
, so that the compiler can safely infer all types:
return Optional.ofNullable(Iterables.getOnlyElement(list, (T) null));
Also, you can simplify your code:
return Collectors.collectingAndThen(Collectors.toList(),
list -> Optional.ofNullable(Iterables.getOnlyElement(list, (T) null)));
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论