获取编译时错误 推断变量 T 具有不兼容的界限

huangapple go评论74阅读模式
英文:

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 &lt;T&gt; Collector&lt;T, ?, T&gt; onlyElement() {
        return Collectors.collectingAndThen(Collectors.toList(), Iterables::getOnlyElement);
    }

    public static &lt;T&gt; Collector&lt;T, ?, Optional&lt;T&gt;&gt; optionalElement() {
        return Collectors.collectingAndThen(Collectors.toList(), (list) -&gt; {
            return Optional.ofNullable(Iterables.getOnlyElement(list, (Object)null));
        });
    }

    public static &lt;T&gt; Collector&lt;T, ?, List&lt;T&gt;&gt; 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 -&gt; Optional.ofNullable(Iterables.getOnlyElement(list, (T) null)));

huangapple
  • 本文由 发表于 2020年10月6日 07:47:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/64217556.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定