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

Stefan Schulz schulz at the-loom.de
Tue Jan 5 05:56:01 PST 2010


You are mistaken in that the loop happens outside the utility method. 
The desugaring converts the invocation statement into a method call with 
an appropriate (transparent) lambda expression.

It's the "for" that confuses a reader, and I don't think it to be that 
helpful.

I'd also suggest not to use a "last block may be invocation statement" 
approach, but make the method declaration more accessible and obvious to 
a reader. For example, using a similar definition to its usage also 
implying transparency wrt. exceptions, break, continue and return:

public static <K, V>
void forEachEntry(K, V as block : Map<K, V> map) {
     for (Map.Entry<K,V> entry : map.entrySet()) {
         block.invoke(entry.getKey(), entry.getValue());
     }
}

Stefan

Am 05.01.2010 14:19, schrieb Gernot Neppert:
> Yes, but this is not the problem I'm seeing. Of course, if the
> declaration were something like:
>
> public final class Utils
> {
> public static<K,V,throws X>
> void for eachEntry(Map<K,V>  map, #void(K,V) throws X} block)
>          throws X {
>      for (Map.Entry<K,V>  entry : map.entrySet()) {
>          block.invoke(entry.getKey(), entry.getValue());
>      }
>
> }
> }
>
> we'd just need to do a "import static Utils.*;" to get the method into scope.
> I'm asking: how is the compiler de-sugaring this invocation:
>
> for eachEntry(String name, Integer value : map) { }
>
> into an iteration over the map?
> Please note that only the *definition* of the method body contains the
> code that does the actual iteration.
>
>
>
> 2010/1/5 Peter Levart<peter.levart at marand.si>:
>> On Tuesday 05 January 2010 09:24:31 Gernot Neppert wrote:
>>> Or, rephrased after Darwin: Where's the missing link?
>>
>> I think the example assumes that the "for eachEntry" method declaration is in scope when you are "invoking" the method (either you are invoking it from within an instance method of the same class or subclass or from an instance method of the inner class.
>>
>> Other possibility for "shorter" syntax is that you invoke a static method and use a static include.
>>
>> Regards, Peter
>>
>


More information about the closures-dev mailing list