Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lambdas and generics in Java 8

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?

like image 390
Natan Cox Avatar asked Dec 07 '12 10:12

Natan Cox


People also ask

What are lambda in Java 8?

A lambda in Java essentially consists of three parts: a parenthesized set of parameters, an arrow, and then a body, which can either be a single expression or a block of Java code. In the case of the example shown in Listing 2, run takes no parameters and returns void , so there are no parameters and no return value.

Can lambda expressions be generic?

A lambda expression can't specify type parameters, so it's not generic. However, a functional interface associated with lambda expression is generic.

Does Java 8 have lambda?

Lambda Expressions were added in Java 8. A lambda expression is a short block of code which takes in parameters and returns a value. Lambda expressions are similar to methods, but they do not need a name and they can be implemented right in the body of a method.

What is generics in Java 8 explain?

Generics means parameterized types. The idea is to allow type (Integer, String, … etc., and user-defined types) to be a parameter to methods, classes, and interfaces. Using Generics, it is possible to create classes that work with different data types.


1 Answers

@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.

like image 185
Natan Cox Avatar answered Oct 03 '22 18:10

Natan Cox