The Source for Java Technology Collaboration
User: Password:
Register | Login help    

Search

Online Books:
java.net on MarkMail:


Closure and collection integration

Posted by forax on September 8, 2006 at 12:39 AM PDT

The closure proposal doesn't define how closure and collections will work together. It's reasonable to say that this API will exist because closure in order to be accepted by the community must be well integrated with collections. After all, java.util is the second more used package after java.lang.
But that is not so easy.

In a dream world, collection should have method like forEach in their interface, but there is no way to add a method in an existing interface without breaking the sacredsanct backward compatibility.
So a code like that is not possible :

 List list=Arrays.asList("closure","collection");
 List list2=list.forEach(int(String s) {
   return s.length();
 });

In my opinon, there are two other ways to do something similar. The first one consists in reversing the problem, if you can't add a method on collection, you can add it to closure.
So closure can have a base class, say java.lang.Function, that defines methods that take collections as parameter.
So the privous code will become that :

 List list2=int(String s) {
   return s.length();
 }.forEach(list);

I'm not a big than of this solution, it's too PERL-like, you don't know what an instruction do without read the whole block.

The other solution is to defined methods that use closure in a class like java.util.Collections that already contains lot of helper methods and to use an import static.
In this case, the code will be :

 import static java.util.Collections.*;
 
 List list2=forEach(list,int(String s){
   return s.length();
 });

Or with the inline syntax of the closure proposal :

 import static java.util.Collections.*;
 
 List list2=forEach(list) int(String s) {
   return s.length();
 };
In that case forEach is just another method in the class Collections.
 package java.util;
 public class Collections {
   public <T,U> List<U> forEach(List<T> list,U(T) function) {
     ...
   }
 }

Any other ideas ?

Related Topics >> Open JDK      
Comments
Comments are listed in date ascending order (oldest first)