Created
December 8, 2016 22:03
-
-
Save Pikuseru/db148cad8314bb31b0adbba611703449 to your computer and use it in GitHub Desktop.
Java IIFE and shared scoped variables
This file contains 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
interface Function { | |
Object call(Object argument); | |
} | |
interface A { | |
void set(String object); | |
String get(); | |
} | |
interface B { | |
void set(String object); | |
String get(); | |
} | |
class Pair { | |
A a; B b; | |
Pair(A a, B b) { | |
this.a = a; | |
this.b = b; | |
} | |
void puts(java.io.PrintStream stream) { | |
stream.println(String.format("a:%s, b:%s", a.get(), b.get())); | |
} | |
} | |
public class Test { | |
public static void main(String[] args) { | |
Pair pair = pair("foo"); | |
pair.puts(System.out); | |
pair.a.set("bar"); | |
pair.puts(System.out); | |
pair.b.set("baz"); | |
pair.puts(System.out); | |
} | |
private static Pair pair(String string) { | |
return (Pair)(new Function() { | |
String shared; | |
public Object call(Object argument) { | |
shared = (String) argument; | |
A a = new A() { | |
public void set(String object) { | |
shared = object; | |
} | |
public String get() { | |
return shared; | |
} | |
}; | |
B b = new B() { | |
public void set(String object) { | |
shared = object; | |
} | |
public String get() { | |
return shared; | |
} | |
}; | |
return new Pair(a, b); | |
} | |
}).call(string); | |
} | |
} |
This file contains 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
> javac Test.java && java Test | |
a:foo, b:foo | |
a:bar, b:bar | |
a:baz, b:baz |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment