1

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()));
    }
};
3
  • If you convert the lambda to a regular function you cannot directly assign it to factory. More context is needed to understand what you're trying to do. Commented May 4, 2021 at 4:05
  • are you using the lambda parameter lv? why not start with a new Callback<>(){} implementation and then transform the code for readability. Commented May 4, 2021 at 4:18
  • 1
    Please don't vandalize your posts. By posting on the Stack Exchange network, you've granted a non-revocable right, under the CC BY-SA 4.0 license, for Stack Exchange to distribute that content (i.e. regardless of your future choices). By Stack Exchange policy, the non-vandalized version of the post is the one which is distributed, and thus, any vandalism will be reverted. If you want to know more about deleting a post please see: How does deleting work? Commented Jun 7, 2021 at 3:30

1 Answer 1

1

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()));
            }
        };
    }
};
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you so much, this helps me see the outline of how these works!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.