convert method to java 8 lambda

扶醉桌前 提交于 2020-01-07 02:15:11

问题


How to write this method in functional programming by using Java 8 lambda / stream() in a short more intuitive way?

int animation = R.style.DialogAnimationSlideHorizontal;
String body;
String subject = mSubjectView.getText().toString();
BaseDialog dialog = dialogFactory.getType(DialogTypes.DIALOG_FULL);

if (!checkFields()) {
    // one of the recipients is invalid.
    body = getString(R.string.bad_address);
    dialog.showDialog(body, animation, new DialogBuilder.Positive() {
        @Override
        public void handleClick(DialogInterface dialogInterface, View view) {
            // do nothing
        }
    });
} else if (Helpers.isEmpty(subject)) {
        // Yup, empty... send the message without a subject?
        body = getString(R.string.empty_subject_compose);
        dialog.showDialog(body, animation, new DialogBuilder.Positive() {
            @Override
            public void handleClick(DialogInterface dialogInterface, View view) {
                // user accepted to send anyway.
                mWebView.getComposeContent();
            }
        });
} else {
    // everything is correct! send the message.
    mWebView.getComposeContent();
}

回答1:


Replace all anonymous classes with lambdas like

new DialogBuilder.Positive() {
    @Override
    public void handleClick(DialogInterface dialogInterface, View view) {
       ...
    }
}

               |
               V

(dialogInterface, view) -> { /*do nothing*/ }
(dialogInterface, view) -> { mWebView.getComposeContent(); }

And I don't see how Stream API can be applied here.



来源:https://stackoverflow.com/questions/37438097/convert-method-to-java-8-lambda

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