Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert Callback into Java 8 Lambda expression

In my current project, I'm working on a rather simple JavaFX GUI containing a TreeTableView. To initialize the View I have the following code.

cmdNrColumn.setCellFactory(new Callback<TreeTableColumn<Command, Command>, TreeTableCell<Command, Command>>() {
    @Override public TreeTableCell<Command, Command> call(final TreeTableColumn<Command, Command> p) {
        return new TreeTableCell<Command, Command>() {
            @Override protected void updateItem(Command item, boolean empty) {
                super.updateItem(item, empty);

                TreeTableView treeTable = p.getTreeTableView();

                if (getIndex() >= treeTable.getExpandedItemCount()) {
                    setText(null);
                } else {
                    TreeItem<Command> treeItem = treeTable.getTreeItem(getIndex());
                    if (item == null || empty || treeItem == null || treeItem.getValue() == null) {
                        setText(null);
                    } else {
                        setText(Integer.toString(item.getCmdNr()));
                    }
                }
            }
        };
    }
});

Being new to Java 8 I'm not quite sure if and how this could be simplified to a Lambda expression.

Any help or tutorial on how to convert complicated and nested calls to a Lambda expression would be kindly appreciated

Thanks!

like image 661
NPortmann Avatar asked Jun 01 '14 10:06

NPortmann


People also ask

Is lambda a callback?

Lambda function are anonymous functions. Callback can be named or anonymous. So all lambda functions can be a callback function but not all callback function can be lambda function.

What is the lambda expression in Java 8?

Lambda Expressions were added in Java 8. A lambda expression is a short block of code which takes in parameters and returns a value. Lambda expressions are similar to methods, but they do not need a name and they can be implemented right in the body of a method.

Can lambda expression have return statement?

A return statement is not an expression in a lambda expression. We must enclose statements in braces ({}). However, we do not have to enclose a void method invocation in braces. The return type of a method in which lambda expression used in a return statement must be a functional interface.


1 Answers

You can transform the outer anonymous class into a lambda expression:

cmdNrColumn.setCellFactory(p ->
    new TreeTableCell<Command, Command>() {
        @Override
        protected void updateItem(Command item, boolean empty) {
            // ...
            TreeTableView treeTable = p.getTreeTableView();
            // ...
        }
    });

However, the same transformation isn't possible for the inner anonymous class, because TreeTableCell is an abstract class, and lambda expressions can only be used for interfaces.

like image 190
nosid Avatar answered Oct 05 '22 21:10

nosid