why unrestricted closures are always void?
Vladimir Kirichenko
vladimir.kirichenko at gmail.com
Sat Nov 15 18:53:49 PST 2008
Vladimir Kirichenko wrote:
> It's not void neither in closure nor in method.
Aha, have got my mistake about return meaning in this case. But in this
case:
method f in class test.Test cannot be applied to given types
required: int,{int ==> int}
found: int,{int ==> void}
f(int i : 3) { out.println(i);}
there is no way to satisfy "required" type with control syntax.
Another one is for abstraction with return type:
static for int eachEntry(int[] values, { int ==> void } block) {
for (int p : values)
block.invoke(p);
return 1;
}
this one will not compile:
int y = for eachEntry(int i : v) {
System.out.println(i);
}
So there is mutually exclusive cases:
1. I can use "break" or "continue" only with "for xxx" invocation - but
in this case return value is unaccessible.
2. I can access return value - but cannot use "continue" and "break"
features of unrestricted closure.
Test.java:101: continue outside of loop
int x = eachEntry(v, {int i ==> if (i > 3) continue;
out.println(i);});
but this will compile and work:
int x = eachEntry(v, {int i ==> if (i > 3) return;
out.println(i);});
but in this notation there are 2 things:
1. code after this loop will not be executed.
2. return value will never be acquired.
Another example:
//compilation ok
{int ==> void} t = {int i ==> if (i >3) return; out.println(i);};
//compilation ok
static {int ==> void} terminator() {
return {int i ==> out.println(i);};
}
static {int ==> void} terminator() {
return {int i ==> if (i > 3) return; out.println(i);};
}
// oops
Test.java:86: missing return value
return {int i ==> if (i > 3) return; out.println(i);};
what is the difference? I can define local variable but cannot define a
value?
Ok, lets hack it:
//just to return argument
static <T> T id(T t) {return t;}
//compiles and works.
{int ==> void} t = {int i ==> if (i >3) return; out.println(i);};
{int ==> void} t2 = id(t);
int x = eachEntry(v, t2);
But this looks crazy - return defined elsewhere (possibly in different
class) terminates local method. Imagine how collections handling method
will look like, one writing the iteration code which applies closure
passed from elsewhere and could not even imagine will the execution be
continued after iteration or not:
void m ({int ===> void} t) {
for(int i: v) t.invoke(i);
System.out.println("who knows if we ever reach here...");
}
Looking to the previous examples I'm thinking - it there sense to be
able to use unrestricted closures as an argument at all?
Or am I missing something?
--
Best Regards,
Vladimir Kirichenko
-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 254 bytes
Desc: OpenPGP digital signature
Url : http://mail.openjdk.java.net/pipermail/closures-dev/attachments/20081116/46d9e2e4/attachment.bin
More information about the closures-dev
mailing list