Converting between structurally compatible function types
Jed Wesley-Smith
jed at wesleysmith.io
Tue Feb 24 02:19:25 UTC 2015
You are asking javac to know that the second type parameter is only used
covariantly (ie. only as a return type), but the compiler cannot know this
unless it goes and inspects every place it is used. This is because Java
has use-site variance, rather than declaration-site variance.
Consider that while a Function<String, Integer>is absolutely acceptable
where you need a Function<String, Object>, a Function<Integer, String> is
not acceptable when a Function<Object, String> is required. This is because
the first parameter is exclusively used as an input parameter. Inputs are
contravariant, and again you can only know this by inspecting the
use-sites, and nothing would prevent someone from casually using the first
type parameter in return position, or vice versa.
Contrast this with Scala that has declaration site variance, using '+' for
covariance and '-' for contravariance. The function definition is actually
Function1[-A, +B], and the compiler bars you from using these incorrectly.
Java can only really support what you want via helper methods that hide the
ugliness, eg:
public <A, B> Function <A, B> covariant(Function<A, ? extends B> f) {
@SuppressWarnings("unchecked")
Function <A, B> fb = (Function <A, B>) f;
return fb;
}
public <A, B> Function <A, B> contravariant(Function<? super A, B> f) {
@SuppressWarnings("unchecked")
Function <A, B> fb = (Function <A, B>) f;
return fb;
}
cheers,
jed
On 24 February 2015 at 04:31, Millies, Sebastian <
Sebastian.Millies at softwareag.com> wrote:
> Hello there,
>
> I have a very basic question: why does the following not compile:
>
> Function<String,Integer> f = s -> 1;
> Function<String,Object> g = f;
>
> After all, I would expect that anywhere where a function from String to
> arbitrary objects is required, I can supply a function to integers in
> particular.
> I guess Java just sees the names are different, and that’s it?
>
> How do I best convert between the two types?
>
>
> n Sebastian
>
>
> Software AG – Sitz/Registered office: Uhlandstraße 12, 64297 Darmstadt,
> Germany – Registergericht/Commercial register: Darmstadt HRB 1562 -
> Vorstand/Management Board: Karl-Heinz Streibich (Vorsitzender/Chairman),
> Eric Duffaut, Dr. Wolfram Jost, Arnd Zinnhardt; -
> Aufsichtsratsvorsitzender/Chairman of the Supervisory Board: Dr. Andreas
> Bereczky - http://www.softwareag.com
>
>
>
More information about the lambda-dev
mailing list