1

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?

lealceldeiro
  • 14,342
  • 6
  • 49
  • 80
Tlaloc-ES
  • 4,825
  • 7
  • 38
  • 84

2 Answers2

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.

CodeMatrix
  • 2,124
  • 1
  • 18
  • 30
1

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.

Zabuzard
  • 25,064
  • 8
  • 58
  • 82