Created
June 7, 2016 13:22
-
-
Save deleter8/ab59465cb3edd14a9ef3a8a3d54a2da5 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class LambdaBehavior { | |
interface Mixin { | |
Map<Mixin, String> backingMap = Collections.synchronizedMap(new WeakHashMap<>()); | |
default String getName() { return backingMap.get(this); } | |
default void setName(String name) { backingMap.put(this, name); } | |
} | |
interface X extends Runnable, Mixin {} | |
static X makeI() { return () -> System.out.println("x"); } | |
static X makeII() { return new X() { | |
@Override | |
public void run() { | |
System.out.println("X"); | |
} | |
}; } | |
static X makeIII(String s) { return () -> System.out.println(s); } | |
@Test | |
public void thing() { | |
X xi1 = makeI(); | |
X xi2 = makeI(); | |
xi1.setName("x1"); | |
xi2.setName("x2"); | |
X xii1 = makeII(); | |
X xii2 = makeII(); | |
xii1.setName("x1"); | |
xii2.setName("x2"); | |
X xiii1 = makeIII(""); | |
X xiii2 = makeIII(""); | |
xiii1.setName("x1"); | |
xiii2.setName("x2"); | |
System.out.println("Lambda with no implicit closure variable:"); | |
System.out.println(xi1.getName()); | |
System.out.println(xi2.getName()); | |
System.out.println("Anonymous class:"); | |
System.out.println(xii1.getName()); | |
System.out.println(xii2.getName()); | |
System.out.println("Lambda with implicit closure variable:"); | |
System.out.println(xiii1.getName()); | |
System.out.println(xiii2.getName()); | |
} | |
} | |
//Outputs: | |
// Lambda with no implicit closure variable: | |
// x2 | |
// x2 | |
// Anonymous class: | |
// x1 | |
// x2 | |
// Lambda with implicit closure variable: | |
// x1 | |
// x2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Expanded on concept found in https://kerflyn.wordpress.com/2012/07/09/java-8-now-you-have-mixins/ to poke further at the behavior of lambdas and anonymous implementations.