Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save stevenschwenke/f7470fc434e3d334436d2c22f05d7f17 to your computer and use it in GitHub Desktop.
Save stevenschwenke/f7470fc434e3d334436d2c22f05d7f17 to your computer and use it in GitHub Desktop.
@FunctionalInterface
public interface SimpleFunctionalInterface {
public int returnAnswerToUltimateQuestion();
}
@Test
public void normalInterfaceOnlyOneAbstractMethod() {
int x = 1;
SimpleFunctionalInterface myInterfaceImpl = () -> {
// x = 2; // impossible
instanz = 3; // possible because member variables are copied when creating lambdas. (http://stackoverflow.com/questions/25055392/lambdas-local-variables-need-final-instance-variables-dont)
// TODO: Why is the class, in which the lambda is defined, copied? I thought that lambdas are "closed" definitions of functionality that can be passed around.
return 0;
};
}
@schauder
Copy link

schauder commented May 14, 2017

I do not like the term copied and I don't like the answers on stackoverflow either ... might want to provide my own.

If a lambda accesses a field, this is what happens (I'm making this stuff up as I go. I did not read the Java specification for this, nor did I look at the source code of javac:

The lambda gets translated into a class, including a constructor.

If the lambda accesses a field of the enclosing class a reference to the instance gets passed into the constructor of the lambda.

=> it can read and write fields
=> it can read the instance, i.e. this but it can't change where this is pointing to. Read up about this in JS why this limitation is a good thing.

If the lambda accesses a local variable (or parameter), that parameter gets passed in as another constructor argument.

=> it can read and write fields of that variable
=> it can read the variable, but it can't change where the pointer to the variable points to.

@stevenschwenke
Copy link
Author

Thanks a lot! Changed my workshop accordingly. Could you please have a look at this commit? It should contain everything important, but a review would be nice. :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment