Is it possible to use lambdas in this case (One method interface)?

China☆狼群 提交于 2021-02-08 07:31:11

问题


I have the following code:

DialogInterface.OnClickListener closeOnOkClickListener = new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            switch (which){
                case DialogInterface.BUTTON_POSITIVE:
                    finish();
                    break;
            }
        }
    };

And I am trying to convert this to a lambda expression but I cannot do it.

Is it possible?

How?


回答1:


It is possible. Every interface which just got one non-default method is an FunctionalInterface. The annotation is just for the compiler to make sure the interface just got one non-default method, if not you get a compiler error.

Try this:

DialogInterface.OnClickListener closeOnOkClickListener = (dialog, which) -> {
    switch (which){
        case DialogInterface.BUTTON_POSITIVE:
            finish();
            break;
    }
};

Check this out for a larger explaination of the FunctionalInterface annotation.




回答2:


Explanation

It is possible as long as the interface only has one (non-default) method, which it has in your case.

Here is the lambda variant:

DialogInterface.OnClickListener closeOnOkClickListener = (dialog, which) -> {
    switch (which) {
        case DialogInterface.BUTTON_POSITIVE:
        finish();
        break;
    }
};

Note that you could improve your code slightly since you only use one of your switch cases:

DialogInterface.OnClickListener closeOnOkClickListener = (dialog, which) -> {
    if (which.equals(DialogInterface.BUTTON_POSITIVE)) {
        finish();
    }
};

Note

The interface should ideally have @FunctionalInterface as annotation to document such an usage.



来源:https://stackoverflow.com/questions/56183531/is-it-possible-to-use-lambdas-in-this-case-one-method-interface

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!