简体   繁体   中英

JavaFX 8 How to do a lambda expression with zero parameters

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.

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.

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
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM