Cool compiler error message with generics

H

HK

import java.util.*;
public class Bla<T> {

private List<T>[] ary = new ArrayList[10];

private class InnerClass<T> {
public void boo() {
List<T> et = ary[0];
}
}
}

Bla.java:8: incompatible types
found : java.util.List<T>
required: java.util.List<T>
List<T> et = ary[0];


It took me some time to realize that the <T> of
InnerClass is a completely different one from
the <T> of Bla. I wonder if the compiler should
rather complain that type variable <T> is
redefined at InnerClass<T>.

Harald.
 
S

Stefan Schulz

It took me some time to realize that the <T> of
InnerClass is a completely different one from
the <T> of Bla. I wonder if the compiler should
rather complain that type variable <T> is
redefined at InnerClass<T>.

Why, it is only consistent with fields, which may have the same name as
well, but different types.
 
T

Thomas Hawtin

HK said:
import java.util.*;
public class Bla<T> {

private List<T>[] ary = new ArrayList[10];

private class InnerClass<T> {
public void boo() {
List<T> et = ary[0];
}
}
}

Bla.java:8: incompatible types
found : java.util.List<T>
required: java.util.List<T>
List<T> et = ary[0];


It took me some time to realize that the <T> of
InnerClass is a completely different one from
the <T> of Bla. I wonder if the compiler should
rather complain that type variable <T> is
redefined at InnerClass<T>.

Obviously not a good idea to reuse generic parameter names in nested
classes. I think the problem is defining lint warnings consistently that
wouldn't complain about, say, having a local and a field with the same name.

You can get something similar at runtime with misuse of class loaders.
If the same class file is loaded by two loaders you can get a class cast
exception claiming that you cannot cast com.mycorp.MyClass to
com.mycorp.MyClass.

Tom Hawtin
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top