3

I know the title isn't terribly descriptive, but I couldn't really come up with something better. This is more about my (lack of) general understanding of generics than about Guava.

Let's suppose I have an interface like this:

public interface HasId {
  String getId();
}

And I have a function declared like this:

private static Function<? extends HasId, String> getId = new Function<HasId, String>() {
    public String apply(HasId input) {
        return input.getId();
    }
};

Why can't I use this function in e.g. an ordering like this (which generates a compiler error that getId is of the wrong generic type):

List<String> ids = ...;
List<SomeTypeImplementingHasId> someStuff = ...;
Ordering<SomeTypeImplementingHasId> byIds = Ordering.explicit(ids).onResultOf(getId);
List<SomeTypeImplementingHasId> sortedByGivenIds = byIds.sortedCopy(someStuff);

I know I can do it with a wrapper function casting it like this:

@SuppressWarnings("unchecked")
<T extends HasId> Function<T, String> getIdFunc() {
    return (Function<T, String>)getId;
}

But isn't there some way that doesn't need this unchecked cast?

Edit: This solved my problem, thanks @Natix & @Jean Logeart:

I first had to get rid of the wildcard in the function declaration:

Function<HasId, String> getId = ...

and then I had to change my ordering to be typed on the super-class also:

Ordering<HasId> byIds = Ordering.explicit(ids).onResultOf(getId);
David
  • 1,359
  • 1
  • 13
  • 20
  • 1
    Just declare the function like this `Function getId`. The wildcard isn't useful there. – Natix Jul 31 '14 at 16:23
  • @Natix Ok, that fixes the transform. Still have an issue using it with Ordering, going to modify the question in a sec. – David Jul 31 '14 at 16:27
  • 1
    [Pretend you're talking to a busy colleague and have to sum up your entire question in one sentence: what details can you include that will help someone identify and solve your problem? **Include any error messages**, key APIs, or unusual circumstances that make your question different from similar questions already on the site.](http://stackoverflow.com/help/how-to-ask) – durron597 Jul 31 '14 at 16:36

1 Answers1

2

You can:

  • Declare Function<HasId, String> getId = ...
  • Declare Function<? super HasId, String> getId = ...

More info: What is PECS (Producer Extends Consumer Super)?

Community
  • 1
  • 1
Jean Logeart
  • 52,687
  • 11
  • 83
  • 118