Luca S.
Luca S.

Reputation: 1162

What is -> operator in Java/JavaFX?

Looking into an open source project in JavaFX I found this lines:

@FXML
private TreeTableColumn<Person, String> firstNameColumn;
@FXML
private TreeTableColumn<Person, String> lastNameColumn;
@FXML
private void initialize() {
    // Initialize the person table with the two columns.
    firstNameColumn.setCellValueFactory(cellData -> cellData.getValue().firstNameProperty());
    lastNameColumn.setCellValueFactory(cellData -> cellData.getValue().lastNameProperty());
 }

I never saw the "->" operator before. What is it?

The signature of setCellvalueFactory is:

setCellValueFactory(Callback< TreeTableColumn.CellDataFeatures< S,T>,
                    ObservableValue< T>> value)

Upvotes: 1

Views: 1871

Answers (2)

JackB.
JackB.

Reputation: 21

Even if you are not using Java 8 this token is used by IntelliJ IDE to make visually shorter your methods.

Upvotes: 1

Roland
Roland

Reputation: 18415

The arrow token in your code is part of a lambda expression. Some say it's the biggest feature that came with Java 8.

One example use case is to improve code readability. Instead of an anonymous class

btn.setOnAction(new EventHandler<ActionEvent>() {

    @Override
    public void handle(ActionEvent event) {
        System.out.println("Hello World!");
    }
});

you could write the same as lambda expression:

btn.setOnAction(
    event -> System.out.println("Hello World!")
);

Upvotes: 4

Related Questions