Type inference: bug or feature?
Justin Dekeyser
justin.dekeyser at gmail.com
Sun Jul 26 17:22:20 UTC 2020
Dear all,
I'm not sure but I think I've found a bug in Java type inference mechanism.
It may also be a feature, so I'll expose the problem to you below; in terms
of Integer, Number and List, although you'll quickly realize it will work
wrong in any similar situation.
Let's assume I have
static <U, V extends U> List<U> emptyList(Class<U> magnet) {
return Collections.emptyList();
}
Then the following codes does not compile (for the same reason):
var x = (List<Integer>) emptyList(Number.class);
List<Integer> x = (List<Integer>) emptyList(Number.class);
incompatible types: List<Number> cannot be converted to List<Integer>
however, the following do compile:
var x = emptyList(Number.class); // inferred to List<Number>
List<Integer> x = emptyList(Number.class); // no mistake here, it's Integer
on the left
Is this the expected behavior? Why does casting operation here interfere
with type inference like this?
Regards,
Justin Dekeyser
<https://www.avast.com/sig-email?utm_medium=email&utm_source=link&utm_campaign=sig-email&utm_content=webmail>
Garanti
sans virus. www.avast.com
<https://www.avast.com/sig-email?utm_medium=email&utm_source=link&utm_campaign=sig-email&utm_content=webmail>
<#DAB4FAD8-2DD7-40BB-A1B8-4E2AA1F9FDF2>
More information about the core-libs-dev
mailing list