I’m trying to understand lambda formatting in Java and could really use some help converting this function into a standard function to see how this works:
Callback<ListView<Contacts>, ListCell <Contacts>> factory = lv -> new ListCell<>() {
@Override
protected void updateItem(Contacts item, boolean empty) {
super.updateItem(item, empty);
setText(empty ? "-" :( "[" + item.getContactID() + "] " + item.getContactName()));
}
};
Advertisement
Answer
Start with the code to create an anonymous Callback object:
Callback<ListView<Contacts>, ListCell<Contacts>> factory = new Callback<>() {
@Override
public ListCell<Contacts> call(ListView<Contacts> lv) {
}
};
Then paste in the right hand side of the -> lambda operator as call()‘s method body. The only modification needed is to make it a return statement:
Callback<ListView<Contacts>, ListCell<Contacts>> factory = new Callback<>() {
@Override
public ListCell<Contacts> call(ListView<Contacts> lv) {
return new ListCell<>() {
@Override
protected void updateItem(Contacts item, boolean empty) {
super.updateItem(item, empty);
setText(empty ? "-" :( "[" + item.getContactID() + "] " + item.getContactName()));
}
};
}
};