Marcus Junius Brutus
Marcus Junius Brutus

Reputation: 27286

incompatible types with type variables

Can anyone tell me why the following fails to compile?

class A<K> {

    public <K> A() {
    }

    public static <K> A<K> create(Class<K> k) {
        return new A<K>();
    }
}


public class B<K, V> {

    A<K> ak;

    public <K, V> B(Class<K> klass, V v) {
         ak = A.create(klass);
    }
}

It fails with:

[javac] /home/.../src/B.java:17: error: incompatible types
[javac]         ak = A.create(klass);
[javac]                      ^
[javac]   required: A<K#2>
[javac]   found:    A<K#1>
[javac]   where K#1,V,K#2 are type-variables:
[javac]     K#1 extends Object declared in constructor <K#1,V>B(Class<K#1>,V)
[javac]     V extends Object declared in constructor <K#1,V>B(Class<K#1>,V)
[javac]     K#2 extends Object declared in class B
[javac] 1 error

This is an SSCCE so please don't ask what I am trying to accomplish.

Upvotes: 0

Views: 1190

Answers (1)

Bozho
Bozho

Reputation: 597116

  • get rid of <K> in the constructor of A
  • get rid of <K, V> in the constructor of B

Constructors do not need to redefine the type parameters of the class. If you do that, they are defined as new type parameters which hide the ones in the class (Eclipse warns you about that).

Upvotes: 5

Related Questions