Reputation: 199
I am still totally confused about Java lambdas/lambda syntax. I read that lambdas take two general forms:
(param1, param2, ...) -> expression;
(param1, param2, ...) -> { /* code statements */ };
OK, fine. And that when the expression doesn't accept parameters (and is said to be empty), the parentheses are still required.
Now, the following code works correctly:
primaryStage.show();
PauseTransition pause =
new PauseTransition(Duration.seconds(3));
pause.setOnFinished(event ->
primaryStage.hide());
pause.play();
But, when I think to myself that primaryStage.hide()
does not require any parameter, I think I can remove the parameter from the lambda expression. This (obeying the rule to keep brackets) gives me the following code:
primaryStage.show();
PauseTransition pause =
new PauseTransition(Duration.seconds(3));
pause.setOnFinished(() ->
primaryStage.hide());
pause.play();
Which doesn't work!!!
I've tried many permutations, to no avail. Despite poring over pages and pages about lambdas I still cant quite get it straight in my head.
I am really struggling with lambdas. Could someone please give me a clear explanation of what is involved.
Upvotes: 1
Views: 735
Reputation: 17132
The .setOnFinished()
method takes an EventHandler
as an argument (which is a functional interface).
It has one method named handle() that takes in a generic type, this is the method whose parameters you should be considering; So you must pass in a parameter to it.
Upvotes: 2
Reputation: 198103
If the method your lambda is implementing has a parameter, you must have one in your argument list even if you don't use it. You indicated that event -> primaryStage.hide()
worked, so you must be implementing a method with a parameter.
This is just like if you were actually implementing that interface with an anonymous class:
new Consumer<Event>() {
@Override public void accept(Event event) { // can't omit the argument!
primaryStage.hide(); // doesn't use the argument
}
}
Upvotes: 1