Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make <T extends E> generic type argument inclusive?

I have an interface:

  /**
   * Getter for any values within the GameObject and it's subclasses. 
   * Used as callback.
   * 
   * Typical implementation would look like:
   *   new ValueGetter<SummonerSpell, String> {
   *     public String getValue(SummonerSpell source) {
   *       return source.toString();
   *     }
   *   }
   * @param <T> 
   * @param <V> Type of value retrieved
   */
  public static interface ValueGetter<T extends GameObject, V> {
    public V getValue(T source);
  }

In one case I want to use the interface with GameObject itself, rather than some subclass. I want to do this in a List of game objects:

  /**
   * Will call the given value getter for all elements of this collection and return array of values.
   * @param <T>
   * @param <V>
   * @param reader
   * @return 
   */
  public <T extends GameObject, V> List<V> enumValues(ValueGetter<T, V> reader) {
    List<V> vals = new ArrayList();

    for(GameObject o : this) {
      vals.add(reader.getValue(o));
    }
    return vals;
  }

But reader.getValue(o) causes compiler error:

incompatible types: GameObject cannot be converted to T
  where T,V are type-variables:
    T extends GameObject declared in method <T,V>enumValues(ValueGetter<T,V>)
    V extends Object declared in method <T,V>enumValues(ValueGetter<T,V>)

My problem as image:

image description

like image 224
Tomáš Zato - Reinstate Monica Avatar asked Nov 01 '22 05:11

Tomáš Zato - Reinstate Monica


1 Answers

public <T extends GameObject, V> List<V> enumValues(List<T> list, ValueGetter<T, V> reader) {
    List<V> vals = new ArrayList();

    for(T o : list) {
        vals.add(reader.getValue(o));
    }
    return vals;
}
like image 122
user2418306 Avatar answered Nov 08 '22 09:11

user2418306