Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lower bounded wildcard not checked against upper bounded type parameter

I wonder why does this piece of code compile successfully?

Source code:

abstract class A<K extends Number>
{
    public abstract <M> A<? super M> useMe(A<? super M> k);
}

Compiled successfully

How does it work and why does this compile? M is any type, so why it can be used?. Should it be: <M extends Number>? This will not compile:

abstract class A<K extends Number>
{
    public abstract <M> A<? super M> useMe(A<M> k);
}

Error message:

type argument M is not within bounds of type variable K where M, K are type variables: M extends Object declared in method useMe(A) K extends Number declared in class A

What is the difference?

like image 810
Pawel Avatar asked Dec 23 '13 23:12

Pawel


People also ask

What is lower bounded wildcard in Java?

Java generics lower bounded wildcard : Lower bounded wildcard is used to restrict the unknown type to be a specific type or a super type of that type using ‘?’ with super keyword.

Is it possible to specify upper and lower bounds for wildcards?

Note: You can specify an upper bound for a wildcard, or you can specify a lower bound, but you cannot specify both. Say you want to write a method that puts Integer objects into a list.

What is the difference between a wildcard and a type parameter?

A wildcard can have only one bound, while a type parameter can have several bounds. A wildcard can have a lower or an upper bound, while there is no such thing as a lower bound for a type parameter. Wildcard bounds and type parameter bounds are often confused, because they are both called bounds and have in part similar syntax. […]

How do you make a lower bound wildcard in Python?

A lower bounded wildcard is expressed using the wildcard character ('? '), following by the super keyword, followed by its lower bound: <? super A>. Note: You can specify an upper bound for a wildcard, or you can specify a lower bound, but you cannot specify both.


1 Answers

This compiler behavior was discussed on this Eclipse bug. Originally, the Eclipse compiler did error for the expression in your example, while javac did not. Although I haven't yet searched the JLS directly, the consensus seems to be that there is nothing in the spec requiring lower bounded wildcards to be checked against type parameter bounds. In this situation it's ultimately left to the caller to assign a type that satisfies the constraints (as surmised by Stephan Herrmann on that post).

like image 71
Paul Bellora Avatar answered Oct 24 '22 09:10

Paul Bellora