this should not refer to the lambda

Rémi Forax forax at univ-mlv.fr
Sun Feb 21 07:26:08 PST 2010


I've a bad feeling about 'this' referring to the lambda an not to the 
enclosing object.
I've tried to summarize my grievances, some had been already reported by 
Josh and Neal.

1) only few existing inner classes contains one recursive method
     so adding a special syntax for a corner case doesn't worth it.
    Moreover, recursive method often have more parameters,
    a counter, a mutable object etc that are used during the recursion.
    but not needed outside. This will not fit well with lambda
    which often must respect a given signature.

2) If 'this' allow to reference the current lambda,
     for completeness, what is the syntax to reference
     an enclosing lambda in a lambda ?

3) if 'this' refers to the lambda, it doesn't play well with type inference.

4) Here is a snippet with use lambda conversion, function type
     and lambda.

public class MyPanel extends JPanel {
   void createChangeColorButton(Color color, #void(JPanel,Color) action) {
     JButton button = new JButton();
     button.setBackground(color);
     button.add(this);
     button.addActionListener(#(ActionEvent e) {
       action.invoke(this, color);
     });
   }

   public static void main(String[] args) {
     MyPanel panel = new MyPanel();
     panel.createChangeButton(Color.RED, #(JPanel panel, Color color) {
       panel.setBackground(color);
     });
     panel.createChangeButton(Color.BLUE, #(JPanel panel, Color color) {
       panel.setForeground(color);
     });
     ...
   }
}

     A lambda statement really looks like a block and not like an object 
creation.
     If 'this' refers to the lambda itself, it's error prone.

     In the example, color and action are not declared final,
     because there are not modified.
     This trick let the developer to care less about scopes.
     But if 'this' refers to the lambda, scopes are important.
     The 'this as the current lambda' feature seems to go in the wrong 
direction.

For my students, I would love to explain lambda without having to explain
inner classes and anonymous classes.
Even if Java developers are used to use inner classes,
don't forget that scoping rules are complex to understand for rookies
(particularly if your first language is C and not Javascript :)
Lambdas are by itself a concept which is not simple to grasp,
please don't pollute it with unnecessary feature.

Just a last example: I don't want to explain why 'this' doesn't mean
the same thing in the two codes:

Object[] array = { this };    // here this doesn't refer to the array

#Object() fun = #() (this);  // here this refer to the lambda ??


Rémi





More information about the lambda-dev mailing list