Let's talk about functional interfaces. Suddenly, take a look at the code below.
Func.java
interface Foo {
public Function<String,String> doIt(Function<Integer,String> f);
}
Main.java
Foo foo = f -> x -> "ABC" + f.apply(x.length());
System.out.println(foo.doIt(x -> x + "$").apply("DEF"));
This is a lambda expression.
Let's go back to the basics of lambda expressions and write Main.java
without omitting it.
Main.java
Foo foo =
(Function<Integer,String> f) ->
{return (String x) -> {return "ABC" + f.apply(x.length());};}
It may be too long to understand, but let's look at this part. The point is -Which lambda expression defines which functional interface ・ Understand the return value at a certain point in time I think there are two points. So I will always be aware of this.
The above code is at the beginning
public Function<String,String> doit(Function<Integer,String> f)
Is the definition of.
So the argument is Function <Integer, String>
.
Make sure you haven't defined this Function yet.
Next, let's look at the return value Function <String, String>
.
(String x) -> {return "ABC" + f.apply(x.length());}
Takes a String type as an argument and returns a String type. The processing of the return value Function is defined here.
The definition of doIt and the definition of the return value of doIt have been made.
Next is the definition of the argument Function <Integer, String>
.
This is done on the second line of Main.java
.
foo.doIt(x -> x + "$").apply("DEF")
That is x-> x +" $ "
.
If you dare to rewrite it
foo.doIt((Integer x) -> {return x + "$";}).apply("DEF")
It will be. It takes an Integer type as an argument and returns a String type.
Now that we have checked each definition, let's take a look at the flow of values.
First, doIt ()
is called, passing the function definition (x-> x +" $ "
).
It then returns another function definition (x->" ABC "+ f.apply (x.length ())
).
By the time doIt is executed, the value is still in the function definition.
A concrete value is generated by executing ʻapply ("DEF") , which is linked to
doIt () `.
" DEF "
is passed to the argument of Function <String, String>
returned from doIt ()
.
When I try to substitute the value,
"ABC" + f.apply("DEF".length())
It means that.
The argument Function <Integer, String> f
is executed using the Integer type of"DEF" .length ()
.
"DEF".length() + "$"
Here, the String type " 3 $ "
is returned.
Then the return function of doIt ()
is
"ABC" + "3$"
And the final value is " ABC3 $ "
.
I tried to explain lambda in lambda. If you have any opinions or supplements, thank you.
Recommended Posts