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?
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.
A lambda expression can't specify type parameters, so it's not generic. However, a functional interface associated with lambda expression is generic.
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.
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.
@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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With