2

I am new to Generics and trying to understand why this code compiles:

public Collection<Class<Subclass>> testFunction() {

    return Collections.singleton(Subclass.class);
}

And this code doesn't:

public Collection<Class<? extends SuperClass>> testFunction() {

    return Collections.singleton(Subclass.class);
}

My SubClass looks like this:

public class Subclass extends SuperClass{

}
Vaibhav
  • 106
  • 9
  • 1
    both of them should compile fine (java 8), the given question doesn't relate to this issue – Andrew Tobilko Dec 21 '16 at 12:10
  • @Eran it that might depend on the Java version you're using, i.e. if the type inference works correctly `Collections.singleton(Integer.class);` should create a `Collection>` but if it doesn't (and older compilers had problems here) you'll get a type conflict. – Thomas Dec 21 '16 at 12:14
  • @Eran On eclipse-neon, with jdk 8 it gives the following error message: Type mismatch: cannot convert from Set> to Collection> – Vaibhav Dec 21 '16 at 12:14
  • 2
    @Vaibhav Eclipse has it's own compiler (`eclipsec`), but it works fine for mars. You can help out the compiler by providing the explicit type: `Collections.>singleton(Subclass.class);` – Jorn Vernee Dec 21 '16 at 12:18
  • @Vaibhav I am running eclipse-neon with JDK8 ... and I dont get that error. Could it be that you enabled the "compatibility" mode to java7 within your project/workspace preferences? – GhostCat Dec 21 '16 at 12:20
  • @JornVernee Yes, It works for me on Mars too. – Vaibhav Dec 21 '16 at 12:34

1 Answers1

3

The above compiles fine with Java8:

class SuperClass { }
class Subclass extends SuperClass{ }

class Test {
  public Collection<Class<? extends SuperClass>> testFunction() {
    return Collections.singleton(Subclass.class);
  }
}

The point is: with Java 8, type inference was heavily reworked and improved.

So my guess here is: this doesn't compile for you because you are using Java 7; where simply spoken the compiler wasn't "good enough" to correctly resolve such kind of code.

GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • Here's the problem that I was facing. Your code compiles on java8 for me too now. Earlier eclipse didn't build the project with java8 compiler hence the error was there. – Vaibhav Dec 22 '16 at 11:00