David Urry
David Urry

Reputation: 825

How do I do a set of a generic value?

I have the following defined:

public class myClass<T> {
    private T value;

    protected <T> void setValue(T value) {
        if (value != null) // optional
            this.value = value;
    }
}

However I get a compilation error with this:

Type mismatch: cannot convert from T to T

(I know, helpful and logical right?).

What's the proper way to setup this method? Also note, the signature is setup in an abstract class like this:

@SuppressWarnings("hiding")
protected abstract <T> void setValue(T value);

Upvotes: 0

Views: 229

Answers (2)

ernest_k
ernest_k

Reputation: 45319

You have two unrelated T types. In your method declaration, <T> re-declares a type T, hiding the class-level type variable.

In short, you don't need the method to be generic, because you want setValue to take the type declared on the class. Because the type parameter is available throughout the class, your method should be as simple as:

protected void setValue(T value) {
    if (value != null)
        this.value = value;
}

If your abstract class is generic too, then the same correction needs to be made in it too. Otherwise, you need to revisit its design as having a method taking randomly typed values isn't exactly right.

Upvotes: 2

Lino Contreras
Lino Contreras

Reputation: 89

You already have defined T at class level, if you put it again in the method it takes it as another T. Look at the error message I get when trying to compile your code.

MyClass.java:6: error: incompatible types: T#1 cannot be converted to T#2
        this.value = value;
                     ^
  where T#1,T#2 are type-variables:
    T#1 extends Object declared in method <T#1>setValue(T#1)
    T#2 extends Object declared in class MyClass
1 error

Just remove the second declaration of T and it will compile as intended.

public class MyClass<T> {
    private T value;

    protected void setValue(T value) {
        if (value != null) {
            this.value = value;   
        }
    }
}

Upvotes: 1

Related Questions