Converting between structurally compatible function types
Samir Talwar
samir at noodlesandwich.com
Mon Feb 23 21:17:13 UTC 2015
Java can't, in general, assign a value to another of the same type with
different generic parameters. Just like there's no implicit conversion from
List<String> to List<Object>, you can't convert Function objects either.
My preferred way of doing this would be to use the fact that Function is
really a class with the method `apply` and assign a method reference
instead:
Function<String, Object> g = f::apply;
Cheers,
— Samir.
On Mon, Feb 23, 2015 at 5:36 PM, Millies, Sebastian <
Sebastian.Millies at softwareag.com> wrote:
> sorry for the noise, figured out how to use the identity function for this:
>
> Function<Integer,Object> id = n -> n
> g = id.compose(f);
>
> -- Sebastian
>
> -----Original Message-----
> From: lambda-dev [mailto:lambda-dev-bounces at openjdk.java.net] On Behalf
> Of Millies, Sebastian
> Sent: Monday, February 23, 2015 6:32 PM
> To: lambda-dev at openjdk.java.net
> Subject: Converting between structurally compatible function types
>
> 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