问题
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