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!
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With