Home > database >  Can't return variable from lambda in Java
Can't return variable from lambda in Java

Time:11-26

so I have this method:

    public void trackSelection() {
    showtimesListView.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, currentValue) ->
            System.out.println(currentValue));
}

It tracks the currently selected item in my listview component in JavaFX. It works great, however I want to change the method to return the string currentValue, instead of just printing it so I can access it from another part of my project.

Here is where I am failing:

public String trackSelection() {
    showtimesListView.getSelectionModel().selectedItemProperty().addListener((observable, oldValue, currentValue) ->
            return (currentValue);
}

For some reason I can only seem to have the void return type on the end of the lambda expression, does anyone know how I can resolve this so I can return a string?

CodePudding user response:

With your lambda you are effectively implementing a listener interface, e.g., like https://docs.oracle.com/javase/8/javafx/api/javafx/beans/value/ChangeListener.html. As you can see, it has exactly one method with return type void.

What you most likely need to do is to provide the currentValue to the observable. But then again, you haven't provided any info what you actually want to achieve.

CodePudding user response:

Lambda expressions don't appear out of nowhere, they conform to a Functional interface, which is an interface declaring a single abstract method. And lambda is an implementation of the contract defined by the interface.

What you want is not possible because can't change a contract which is coming from JavaFX.

For more information on Lambda expressions, refer to the official tutorial provided by Oracle.

  • Related