0

This is in a javafx program and it runs.

button.setOnAction(_ ->{
    int side = 0;
    Random rand = new Random();
    side = rand.nextInt(2);
    if(side == 0){
       //code here
    else{
       //code here
    }
});

A long version of this functionality would be to create the class that implements the EventHandler. Then create a instance of that class for the button.setOnAction. I do not understand how the lambda works the same as the longer code below. How does it know to use the EventHandler functional interface. I watched many YouTube videos that do not go into the details which is why I ask here.

class Handler implements EventHandler<ActionEvent>{
    @Override
    public void handle(ActionEvent actionEvent) {
        int side = 0;
        Random rand = new Random();
        side = rand.nextInt(2);
        if(side == 0){

        }
        else{

        }
    }
}
5
  • 4
    Because the signature of button.setOnAction is button.setOnAction(EventHandler<ActionEvent>). Commented Jun 24 at 0:16
  • 3
    Brian Goetz elaborates in this answer.
    – trashgod
    Commented Jun 24 at 0:51
  • A lambda expression is simply syntax for implementing a functional interface (an interface with a single abstract method). They provide a less verbose way of implementing such interfaces so that you don't have to write a named or anonymous class. But ultimately, a class is created that implements the functional interface; you just don't see it in the source code. Though just like with an anonymous class, a lambda is both the implementation of an interface and an instantiation of that implementation. In your code, an actual object whose class implements EventHandler is created at runtime.
    – Slaw
    Commented Jun 24 at 17:11
  • How the compiler knows EventHandler<ActionEvent> is the functional interface being implemented is explained by Elliott's comment—it can infer the type from the context.
    – Slaw
    Commented Jun 24 at 17:20
  • Also note that the setOnAction method, at a fundamental level, simply takes the object passed to it as an argument—which must be an implementation of EventHandler<ActionEvent>—and adds it to a collection. Whenever the button receives an ActionEvent, the code will iterate that collection and invoke each appropriate handler's handle method. Research the observer pattern for more information.
    – Slaw
    Commented Jun 24 at 17:27

0

Browse other questions tagged or ask your own question.