Java var and inference type ambiguity
My guess is that the compiler is finding two occurrences of toLowerCase
in the String
class, so it decides to first infer from the second argument, Collectors.counting()
, which is resolved to Object
. This leads the compiler to throw an error because it can't find any toLowerCase()
method accepting an Object
.
If we try to define a method to use it as replacement:
static String toLowerCase(String s) {
return s.toLowerCase();
}
the following would then work:
Collectors.groupingBy(Test::toLowerCase, Collectors.counting()); // compiles ok
But if we introduce another overload, the problem appears again:
static String toLowerCase(String s) {
return s.toLowerCase();
}
static String toLowerCase(String s, Locale locale) {
return s.toLowerCase(locale);
}
Collectors.groupingBy(Test::toLowerCase,Collectors.counting()); // fails again
This is compiler "weakness", at least until this JEP is in place.
I have already answered almost the same exact question here. There is also another answer from JDK core developers too.
There is also yet another question that is very close to yours.
What matters is that this is known to cause a problem, at times, but has a trivial solution - use a lambda
, and thus an explicit type, according to the JLS
.