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

Gernot Neppert mcnepp02 at googlemail.com
Tue Jan 5 06:27:40 PST 2010


Ah, now I finally got it!

I was somehow reading more into the colon than what it actually means.
It's tempting to read this "for eachEntry(String name, Integer value : map)" as

"for each key 'name' and value 'value' from 'map' do..."

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);
}

Thanks a lot for your patience.


> I think that the specification is clear about that.
>
> The following example:
>
> for eachEntry(String name, Integer value : map) { ... }
>
> Is de-sugared into the following standard method invocation:
>
> eachEntry(map, #(String name, Integer value)(...; (Void)null));
>
> So the syntax is similar to standard Java control constructs (for, if, while, etc...) but it actualy translates to method invocation where the body of the controled block becomes the body of the lambda expression which is passed as the last argument to the method.
>
> The "for" method modifier is a signal for the compiler to treat the break/continue statements specified in the body of the controlled block differently then they would normally be treated in a transparent lambda - they transfer control either to the end of the controlled block (continue) or to the end of the invoked "for" method (break).
>
> Peter
>


More information about the closures-dev mailing list