-
Notifications
You must be signed in to change notification settings - Fork 10.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Make Functions.constant covariant in argument type. #1927
Comments
Generics aren't, but specific uses of generic types that happen to be covariant should be -- e.g. most places that accept a Function<F, T> should accept a Function<? super F, ? extends E> where appropriate. Is there a place you cannot make this change to the user of the Function? |
Here's my specific use case. I'd like to have an interface that returns a |
Your solution is just to cast. It feels wrong because you have to suppress class Dummy implements Interface<A, B> { On Tue, Dec 23, 2014 at 5:27 AM, vincentk notifications@github.com wrote:
Kevin Bourrillion | Java Librarian | Google, Inc. | kevinb@google.com |
There are no doubt many plausible workarounds (as it were, I am quite content with mine). It is also a very minor issue. I simply felt it noteworthy that a workaround would seem to be required in the first place. Please do feel free to close it if it isn't worth your time. As "solutions" go though, my proposal would be to make private static class ConstantFunction<D,E> implements Function<D, E>, Serializable {
private final E value;
public ConstantFunction(@Nullable E value) {
this.value = value;
}
@Override
public E apply(@Nullable D from) {
return value;
}
[snip] and either change or provide an alternative to public static <D, E> Function<D, E> constantD(E value) {
return new ConstantFunction<>(value);
}
public static <E> Function<Object, E> constant(E value) {
return new ConstantFunction<>(value);
} Though again, I do agree that this is generics cosmetics, and perhaps not worth the possible API change/extension. |
This same issue affects many dozens of Guava methods, and we didn't want to |
Thanks for your explanation and time. |
Presently, a constant function is provided in the
Functions
class with a type signature as followsPersonally, I think that a type signature as follows would be superior
the reason being that while functions in the "mathematical" sense are co-variant with regard to their argument types, generics in java are not (for well-known reasons).
It's probably not trivial to introduce such a change without triggering a compilation error here or there. Still I think it might be worth considering.
The text was updated successfully, but these errors were encountered: