15

I'm playing with future java 8 release aka JDK 1.8.

And I found out that you can easily do

interface Foo { int method(); }

and use it like

Foo foo = () -> 3;
System.out.println("foo.method(); = " + foo.method());

which simply prints 3.

And I also found that there is a java.util.function.Function interface which does this in a more generic fashion. However this code won't compile

Function times3 = (Integer triple) -> 3 * triple;
Integer twelve = times3.map(4);

And it seems that I first have to do something like

interface IntIntFunction extends Function<Integer, Integer> {}

IntIntFunction times3 = (Integer triple) -> 3 * triple;
Integer twelve = times3.map(4);

So I'm wondering if there is another way to avoid the IntIntFunction step?

Natan Cox
  • 1,495
  • 2
  • 15
  • 28
  • 6
    `Mapper times3` maybe? – Joop Eggen Dec 07 '12 at 10:40
  • 6
    Now that I was beginning to understand generics, they come with THIS :-(... – SJuan76 Dec 07 '12 at 10:44
  • 1
    In fact, in the latest build, there is no more an interface Mapper. It is called [Function](http://www.dalorzo.com/jdk8/javadocs/java/util/function/Function.html) now. There are some primitive versions called [IntFunction](http://www.dalorzo.com/jdk8/javadocs/java/util/function/IntFunction.html), [LongFunction](http://www.dalorzo.com/jdk8/javadocs/java/util/function/LongFunction.html) and [DoubleFunction](http://www.dalorzo.com/jdk8/javadocs/java/util/function/DoubleFunction.html). – Edwin Dalorzo Dec 08 '12 at 13:12
  • 1
    `Function times3` with current JDK8 – Natan Cox Dec 02 '13 at 14:40

1 Answers1

5

@joop and @edwin thanks.

Based on latest release of JDK 8 this should do it.

IntFunction<Integer> times3 = (Integer triple) -> 3 * triple;

And in case you do not like you can make it a bit more smooth with something like

IntFunction times3 = triple -> 3 * (Integer) triple;

So you do not need to specify a type or parentheses but you'll need to cast the parameter when you access it.

Natan Cox
  • 1,495
  • 2
  • 15
  • 28