|
|
||
Rémi Forax's BlogNovember 2007 ArchivesJava 7 - Extension methodsPosted by forax on November 29, 2007 at 03:15 AM | Permalink | Comments (12)Recently, Neals, Peter and Stephen blog about extension methods. Why i hate (yes hate) use-site extension ?
What i love (yes love) with Java is the fact that i
can take a look to a screen over one of my student
shoulder and be able to say is the snippet i see
is correct or not.
Demonstration. Do you understand this code ?
...
String text=...
for(int i=0;i<text.size();i++) {
System.out.println(text.charAt(i));
}
Hum, i have forget to say that the begining of the file contains that declaration: import static Strings. and that the class Strings is defined like that:
public class Strings {
public static int size(String s) {
return s.trim().length();
}
}
I'am sure i will hate that.
Furthermore, import static has already some limitations, the code below doesn't compile. This case is currently rare but with extension methods it will be more frequent.
import static java.util.Arrays.*;
public class StaticImport {
public static void main(String[] args) {
toString(args);
}
}
Why i prefer declaration-site extension methods ? It's definitely a good property of a language to be able to understand a code that deals with some java.util.Lists, just by knowing the declaration of this type. If i don't know how to use it, i can just to browse its code. After that, because i have a good brain storage device, i will be able to understand ALL codes that deals with java.util.List. Another proposed syntax I think there is some problems with the syntax proposed by Peter.
package java.util;
public interface List<E> … {
…
void sort() import static java.util.Collections.sort;
…
}
Here is my proposed syntax, allow to declare static method in interfaces (in the same time, we close one the top 25 RFE Bug 4093687) and add some sugar in the compiler.
package java.util;
public interface List<E> … {
…
@ExtensionMethod
static <T extends Comparable<? super T>> void sort(List<T> list) {
java.util.Collections.sort(list);
}
…
}
Like other proposed syntax, the compiler is modified to transform an instance call to a static call. The following code List<String> list=... list.sort();is rewritten to List<String> list=... List.sort(list); @ExtensionMethod (borrowed from Stephen blog) like @Override is not mandatory and tells the compiler to verify that the first parameter of the static method is the same type that the declaring interface.
I wait your comments, | ||
|
|