Virtual extension methods -- a strawman design

Rémi Forax forax at univ-mlv.fr
Sat May 15 10:09:40 PDT 2010


Le 15/05/2010 07:22, Neal Gafter a écrit :

[...]

> We explored static extension methods, but they are pretty unsatisfying; it
>    
>> is impossible for an implementation to provide a better implementation.
>>      
>
> Can you please give specific examples of the issues you anticipate with the
> specific closurizations you want to do in particular APIs?
>
>    

I think I can :)
Let say we want to add a method forEach in Collection:

public interface Collection<T> {
   ...
   public void forEach( void(T) lambda)
     default Collections.forEach(void(T));
}

And in Collections:

public static <T> void forEach(Collection<T> c, void(T) lambda) {
   for(T t: c) {
    lambda.invoke(t);
   }
}

So it will work with a TreeSet:
TreeSet<String> set = ...
set.forEach((String s){
   System.out.println(s);
});

But because the default implementation use an Iterator,
and maintaining a cursor on a tree cost more than
traversing the tree recursively,
the default impelemntation doesn't offer the best performance.

What is cool with this proposal is that you can change
the implementation of forEach for a TreeSet.

public class TreeSet ... {
   public void forEach(void(T) lambda) {
     // faster implementation
   }
}

As far as I know, extension method of C# can't do that.

Rémi


More information about the lambda-dev mailing list