for-loop abstraction: How's this magic gonna work?

Peter Levart peter.levart at marand.si
Tue Jan 5 07:43:54 PST 2010


On Tuesday 05 January 2010 15:27:40 Gernot Neppert wrote:
> Even though the colon simply separates the lambda's argument from the
> method's actual arguments!
> 
> OK, this means that an API has to be carefully designed in order to be
> usable with the Control Invocation Syntax.
> This declaration, for example:
> 
> <K,V,throws X>
> void for printEntry(Writer out, Map<K,V> map, #void(Writer,K,V) throws X} block)
>        throws X {
>    for (Map.Entry<K,V> entry : map.entrySet()) {
>        block.invoke(out, entry.getKey(), entry.getValue());
>    }
> 
> }
> 
> could be (ab)used like this:
> 
> for printEntry(Writer out, String s, Integer v : new StringWriter(), map) {
>   out.println("key = " + s + " value = " + v);
> }

Yes, the API does not have to deal with passing constant values through into the lambda - lambda itself can "close" over such values. The above example feels more natural if you just reuse the "for eachEntry" method from before:

Writer out = new StringWriter();
for eachEntry(String s, Integer v : map) {
  out.println("key = " + s + " value = " + v);
}

Regards, Peter


More information about the closures-dev mailing list