问题
I am looking at the following Stack Overflow answer: How to change Spring's @Scheduled fixedDelay at runtime
And in the code there is the following line:
schedulerFuture = taskScheduler.schedule(() -> { }, this);
I would like to know what the lambda () -> {}
means in that code. I need to write it without using lambdas.
回答1:
Its a Runnable with an empty run
definition. The anonymous class representation of this would be:
new Runnable() {
@Override public void run() {
// could have done something here
}
}
回答2:
Lamda expression is an anonymous function that allows you to pass methods as arguments or simply, a mechanism that helps you remove a lot of boilerplate code. They have no access modifier(private, public or protected), no return type declaration and no name.
Lets take a look at this example.
(int a, int b) -> {return a > b}
In your case, you can do something like below:
schedulerFuture = taskScheduler.schedule(new Runnable() {
@Override
public void run() {
// task details
}
}, this);
回答3:
For lambdas:
Left side is arguments, what you take. Enclosed in ()
are all the arguments this function takes
->
indicates that it's a function that takes what's on the left and passes it on to the right for processing
Right side is the body - what the lambda does. Enclosed in {}
is everything this function does
After you figure that out you only need to know that that construction passes an instance of matching class (look at what's the expected argument type in the schedule()
call) with it's only method doing exactly the same as the lambda expression we've just analyzed.
回答4:
Lambda expressions basically express instances of functional interfaces. In a way Lambda expression will be: (lambda operator params) -> {body}
() -> System.out.println("This means Lambda expression is not taking any parameters");
(p) -> System.out.println("Lambda expression with one parameter: " + p);
来源:https://stackoverflow.com/questions/52292953/meaning-of-lambda-in-java