如何解决Java var 和推理类型歧义
两个调用都是正确的:
Collectors.groupingBy((String s)->s.toLowerCase(),Collectors.counting());
Collectors.groupingBy((String s)->s.toLowerCase(Locale.ENGLISH),Collectors.counting());
从那以后,为什么下面一个是错误的:
Collectors.groupingBy(String::toLowerCase,Collectors.counting());
毕竟String::toLowerCase
不能对应第二个...那IntelliJ为什么说Reference to 'toLowerCase' is ambiguous,both 'toLowerCase(Locale)' and 'toLowerCase()' match
?
String::toLowerCase
必须明确解析为 (String s)->s.toLowerCase()
还是我错过了什么?
当然,如果我为 IntelliJ 添加更多上下文,例如:
Collector<String,?,Map<String,Long>> c = Collectors.groupingBy(String::toLowerCase,Collectors.counting());
这是正确的,但是在 Java 10 var 推理类型上下文中它是错误的:
var c = Collectors.groupingBy(String::toLowerCase,Collectors.counting());
我知道编译器无法推断 counting
的输入类型。如果我写:
Collector<String,Long> counter = Collectors.counting();
var c = Collectors.groupingBy(String::toLowerCase,counter);
它是正确的。因此,为什么编译器不能推断出唯一可接受的形式?
-------EDIT--------
我交替使用 IntelliJ/编译器只是因为我首先使用 IntelliJ 并且报告的错误是:
Reference to 'toLowerCase' is ambiguous,both 'toLowerCase(Locale)' and 'toLowerCase()' match
编译器的错误更难以理解(但包含更多关于推理失败原因的提示),例如:
Demo.java:31: error: incompatible types: cannot infer type-variable(s) T#1,K,A,D,CAP#1,T#2
Collectors.groupingBy(String::toLowerCase,Collectors.counting());
^
(argument mismatch; invalid method reference
incompatible types: Object cannot be converted to Locale)
where T#1,T#2 are type-variables:
T#1 extends Object declared in method <T#1,D>groupingBy(Function<? super T#1,? extends K>,Collector<? super T#1,D>)
K extends Object declared in method <T#1,D>)
A extends Object declared in method <T#1,D>)
D extends Object declared in method <T#1,D>)
T#2 extends Object declared in method <T#2>counting()
where CAP#1 is a fresh type-variable:
CAP#1 extends Object from capture of ?
解决方法
这是编译器的“弱点”,至少在 this JEP is in place 之前是这样。
我已经回答了几乎完全相同的问题 here。还有另一个answer from JDK core developers too。
还有 yet another question 与您的非常接近。
重要的是,这有时会导致问题,但有一个微不足道的解决方案 - 根据 {{ 1}}。
,我的猜测是编译器在 toLowerCase
类中发现了两次 String
,因此它决定首先从第二个参数 Collectors.counting()
推断,该参数解析为 { {1}}。这会导致编译器抛出错误,因为它找不到任何接受 Object
的 toLowerCase()
方法。
如果我们尝试定义一个方法来使用它作为替代:
Object
以下内容将起作用:
static String toLowerCase(String s) {
return s.toLowerCase();
}
但是如果我们引入另一个重载,问题又会出现:
Collectors.groupingBy(Test::toLowerCase,Collectors.counting()); // compiles ok
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。