Type inference: bug or feature?

Justin Dekeyser justin.dekeyser at gmail.com
Mon Jul 27 08:19:21 UTC 2020


Hello,

Thanks for the answer.

Nevertheless, the point was not really about list stuffs, and is not
related to the lack of co/contra variance.
You may replace List with any other generic class  Foo<T> and Integer and
Number with any other class satisfying the same inheritance relations.

The behavior is really about casting, which prevents type inference to work
"as one would expect".
This is even weirder because, in case of lambda expressions, casting does
help in desambiguising the type.

So on the one side, we have a casting operation that helps in type
inference,
on the other side, we have a casting operation that prevents some inference.

I'm really not sure this is no bug :/

Regards,

Justin Dekeyser



On Mon, Jul 27, 2020 at 9:43 AM Florian Weimer <fweimer at redhat.com> wrote:

> * Justin Dekeyser:
>
> > 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?
>
> emptyList() is special, it only works this way because the returned list
> is always empty, so that the element type does not matter.  For any
> other list-returning function, the types List<Integer> and List<Number>
> are not interchangeable because for each type, there are operations
> which are not valid for the other.  That's why we often need wildcards
> once type hierarchies are involved (List<? super Integer> or
> List<? extends Number>, depending on context).
>
> A somewhat similar case is functions which do not return (normally).
> They too can have a very general generic type which does not depend on
> function arguments.
>
> Thanks,
> Florian
>
>


More information about the core-libs-dev mailing list