Closures: why are they so useful?

前端 未结 10 652
渐次进展
渐次进展 2020-12-07 10:04

As an OO developer, maybe I have difficulty seeing its value. What added value do they give? Do they fit in an OO world?

10条回答
  •  温柔的废话
    2020-12-07 10:29

    Closures don't give you any extra power.

    Anything you can achieve with them you can achieve without them.

    But they are very usable for making code more clear and readable. And as we all know clean readable short code is a code that is easier to debug and contains fewer bugs.

    Let me give you short Java example of possible usage:

        button.addActionListener(new ActionListener() {
            @Override public void actionPerformed(ActionEvent e) {
                System.out.println("Pressed");
            }
        });
    

    Would be replaced (if Java had closures) with:

    button.addActionListener( { System.out.println("Pressed"); } );
    

提交回复
热议问题