Java Closures: first prototype を見て2
http://gafter.blogspot.com/2007/10/java-closures-first-prototype.html
昨日の続き
カリー化
// This work is Copyright(c) 2007 Neal M Gafter. All rights reserved. /* * @test /nodynamiccopyright/ * @summary Test capturing variables from closures * @author gafter * * @clean Clarkson5 * @compile -source 7 Clarkson5.java * @run main Clarkson5 */ public class Clarkson5 { public static <T,U,R> {T=>{U=>R}} curry(final {T,U=>R} f) { return {T t=>{U u=>f.invoke(t,u)}}; } public static void main(String[] args) { {Integer,Integer=>Integer} plus1 = {Integer x, Integer y => x+y}; {Integer=>{Integer=>Integer}} plus2 = curry(plus1); int x1 = plus1.invoke(1, 2); int x2 = plus2.invoke(1).invoke(2); if (x1 != 3 || x2 != 3) throw new AssertionError(x1 + " " + x2); } }
インタフェースが勝手に実装される??
// This work is Copyright(c) 2007 Neal M Gafter. All rights reserved. /* * @test /nodynamiccopyright/ * @summary Test the closure conversion and accessing unmodified locals in a closure * @author gafter * * @clean ClosureConversion2 * @compile -source 7 ClosureConversion2.java * @run main ClosureConversion2 */ import java.util.concurrent.Callable; public class ClosureConversion2 { interface I1<T> { T f(T t); } public static void main(String[] args) { System.out.println(g({ String s => "<" + s + ">" }).f("foo")); } static <T> I1<T> g(I1<T> i) { return i; } }
なんでCallable を importしてるのはなんでだろ。
closure と関係ないやつ
// This work is Copyright(c) 2007 Neal M Gafter. All rights reserved. /* * @test /nodynamiccopyright/ * @summary Test disjuntive exception types * @author gafter * * @clean DisjunctiveType1 * @compile -source 7 DisjunctiveType1.java * @run main DisjunctiveType1 */ public class DisjunctiveType1 { interface A { void f(); } static class X0 extends Exception { } static class X1 extends X0 implements A { public void f() { System.out.println("one"); } } static class X2 extends X0 implements A { public void f() { System.out.println("two"); } } public static void main(String[] args) { for (int i=0; i<3; i++) { try { switch (i) { case 0: throw new X1(); case 1: throw new X2(); case 2: System.out.println("three!"); } } catch (X1|X2 ex) { ex.f(); } } } }
たまに欲しいと思ったことはある。
null にキャスト
// This work is Copyright(c) 2007 Neal M Gafter. All rights reserved. /* * @test /nodynamiccopyright/ * @summary Test that we don't allow casting to null * @author gafter * * @clean Null1 * @compile/fail -source 7 Null1.java */ public class Null1 { public static void main(String[] args) { null x = (null) args; } }
なんじゃこりゃ