Why is this assignment involving wildcards legal in Java?
Asked Answered
P

4

7

Most questions about wildcards want to know why something sensible is rejected by the compiler. My question is the opposite. Why is the following program accepted by the compiler?

void test(List<? extends Number> g1, List<? extends Number> g2)
{
    g1 = g2;
}

I tried to explain this from the Java Language Specification, but I have not found the answer. I had the impression from various descriptions of Java generics and wildcards that each use of a wildcard is captured as a completely new type, but apparently not here. I have not found any nasty behavior that follows from this assignment being allowed, but it still seems "wrong".

Pyre answered 17/9, 2020 at 23:27 Comment(0)
H
4

When I face these questions, I approach this in a slightly different manner.

First of all, every single wildcard is captured, everywhere, by javac. In plain english: every time javac "sees" a wildcard it is going to transform that (this is almost accurate as you will see further). Specifically, let's say we have this:

List<? extends Number> list;

javac will transform to:

List<X1> list

where X1 <: Number, where <: means it is a subtype of, as such : X1 is an unknown type that extends Number. This will happen for every single occurrence. And it might be very weird, at first, in some scenarios:

public static void main(String[] args) {
    List<?> l = new ArrayList<String>();
    one(l);
    two(l, l); // fails
}

public static <T> void one(List<T> single){

}

public static <T> void two(List<T> left, List<T> right){

}

capture conversion was applied individually to each List, it's like this happened:

two(List<X1>, List<X2>)

Now to why is your example accepted, is far more interesting, imho. You know that capture conversion is applied, but according to the JLS it is not applied everywhere:

If the expression name is a variable that appears "on the left hand side", its type is not subject to capture conversion.

It's like saying that only values are capture converted, not variables.

So in this case:

g1 = g2;

g1 has not been capture converted, while g2 has. It's like doing:

List<? extends Number> g1 = List<X1> (g2) // pseudo-code

We know that X1 <: Number so, as such List<X1> is a subtype of List<? extends Number>, so the assignment works.

Even if you change ? extends Number to ? (this is not a bounded wildcard anymore), this would still work.

Hasty answered 18/9, 2020 at 20:57 Comment(1)
Very interesting. It seems then that capture conversion is mandatory in some contexts, unlike other conversions that are applied as needed. The JLS is not very clear on this point.Pyre
G
3

List<? extends Number> is best read as:

This is a list of numbers, but, covariantly.

In other words, this is a list of some concrete but unknown type. However, I do know that, whatever type it might be, at least it is either Number or some subclass thereof.

Generics is weird; once you opt into some variance, you get the restrictions to go along with that. In the case of collections, 'covariance' comes with the baggage of 'no adding'.

Try it.

g1.add(XXX);

the only thing that is legal for XXX here? null. That's literally it. The full and complete and exhaustive list of all you can add to this thing. certainly Number x = 5; g1.add(x); is not going to be allowed by javac here.

By writing List<? extends a thingie> you're saying: Yeah, I want that. I'm signing up to this restriction that I get to add absolutely nothing (other than the academic case of literal null). In trade for handcuffing yourself, the things you can pass in for g1 is expanded considerably.

You can also opt into contravariance:

void foo(List<? super Integer> list) {
    list.add(Integer.valueOf(5)); // works!
    Integer x = list.get(0); // no go
}

contravariance is the opposite. add works. get doesn't work. Which in this case means: The type of the expression list.get(0) is just.. Object.


Now that we've covered that:

void test(List<? extends Number> g1, List<? extends Number> g2) {}

means 'my first parameter is a list of numbers, but I opt into covariance handcuffs', and 'my second parameter is a list of numbers, but I also opt into covariance handcuffs for this one too', it now makes sense why java lets you write g1 = g2. g2 is guaranteed to be an X<Y>, where X some concrete subclass of List, and Y is either Number or some subclass thereof.

This is 100% compatible, type-wise, with the notion of 'some sort of list whose type param is some covariant take on Number'. The only thing you can do a List<? extends Number> is to invoke methods of List where any T in the signatures are 'disabled' for parameters, and replaced by the bound (Number) for return types.

That's.. exactly what List<? extends Number> is describing, so it's compatible.

Glossolalia answered 18/9, 2020 at 0:8 Comment(4)
tl;dr the assignment is valid, but you get restrictions downstream.Entoblast
imho, this is entirely correct theory, but misses the question itself. this has to do with capture conversion and how it is (and is not) applied to variables and values.Hasty
@Hasty well, it explains the reasons behind capture conversion. The aim is, once you understand the logic behind what the generics means, you can use that to 'guess' what java's language spec says and get it right pretty much every time. It's either that or memorize the entire JLS :PGlossolalia
@Glossolalia I see your point, thx for the follow-up.Hasty
D
3

"I had the impression from various descriptions of Java generics and wildcards that each use of a wildcard is captured as a completely new type, "

That statement is correct.

So what? You are confusing the type of the object with the type of the variable.

Consider this code:

String s = "abc";
Object o = s;

o has type Object which is assignment compatible with the type of s. But that doesn't mean String and Object are the same type. No different with your example. You have two different List types for the objects, but one type for the variables. Each variable has type List<? extends Number>, so the assignment is fine. When you make the assignment, the object's generic type is List<x> for some completely new unknown type x. But the variable type remains List<? extends Number>.

Derbent answered 18/9, 2020 at 1:51 Comment(1)
this is the correct answer to the question. a fat 1+. I've also added the JLS part that backs this upHasty
A
0

How could it not be valid?

Both variables have identical type (in this case List<? extends Number>), so the compiler must allow assignment of one to the other.


The objects assigned to the variables may have different types, but the variable types are identical, so assignment is always legal.

The compiler does not know or care what the actual type of an object assigned to a variable is, even if it can be determined from the code. It cares only about declared types when checking types.

Atalayah answered 18/9, 2020 at 2:38 Comment(3)
but these are not identical types, every single wildcard (be that bounded or not) is different from each other, the reason is differentHasty
@Hasty Incorrect: the objects may be different types, but the variable types are identical, so assignment is always legal. The compiler does not know or care what the actual type of an object assigned to a variable is, even if it can be determined from the code. It cares only about declared types.Atalayah
@Eugene's explanation is correct. Follow his link to the JLS, or try assigning the list to an Integer variable and see what the error message says. The type of the RHS is a capture type, which is assignable to but not the same as the variable type on the LHS.Pyre

© 2022 - 2024 — McMap. All rights reserved.