java) What is the difference between the general formula and the lambda formula when using this within the anonymous implementation object?

Asked 2 years ago, Updated 2 years ago, 20 views

General expression

commentEdit.setOnKeyListener(new View.OnKeyListener() {
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if(commentEdit.getText().toString().length() == 0) {
            if (listener != null && keyCode == KeyEvent.KEYCODE_DEL && event.getAction() == KeyEvent.ACTION_DOWN) {
                listener.onDeleteKeyPressed(CommentModel.this); 
                return true;
            }
        }
        return false;
    }
});

Ram tea ceremony

commentEdit.setOnKeyListener((v, keyCode, event) -> {
    if(commentEdit.getText().toString().length() == 0) {
        if (listener != null && keyCode == KeyEvent.KEYCODE_DEL && event.getAction() == KeyEvent.ACTION_DOWN) {
            Listener.onDeleteKeyPressed(this); // You can just use this if you use the lambda expression
            return true;
        }
    }
    return false;
});

In the creation of anonymous implementation objects in the first general expression, listener.onDeleteKeyPressed(CommentModel.this);

Currently, CommentModel.this is written, but if you write this, it is the same as in the picture.

Displays errors.

As you can see, the type provided (because it creates an anonymous object type) is OnKeyListener

The required type of onDeleteKeyPressed() is the CommentModel type.

So I had to specify Comment and use this.

However, if you change this anonymous implementation object to Lambda-style, it can be solved only with this.

What's the reason??

java

2022-09-20 17:45

1 Answers

This in the first general expression represents the anonymous inner class because it is written within the anonymous inner class.

The comment model was intended to be delivered as a factor of listener.onDeleteKeyPressed, and this was used, but View.The OnKeyListener is included, so it displays the same error as in the picture. So you have to write CommentModel.this explicitly.

The second lambda this represents the class that surrounds itself because it's written inside the lambda.

This is why there is no problem because this is used as the factor of listener.onDeleteKeyPressed and the CommentModel has been well delivered.

This can be found in Oracle's official documentation. 15.27.2

Unlike code appearing in anonymous class declarations, the meaning of names and the this and super keywords appearing in a lambda body, along with the accessibility of referenced declarations, are the same as in the surrounding context (except that lambda parameters introduce new names).


2022-09-20 17:45

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.