JDK-6487635 : Compiler support for methods as method parameters
  • Type: Enhancement
  • Component: specification
  • Sub-Component: language
  • Affected Version: 1.2.0,6
  • Priority: P5
  • Status: Closed
  • Resolution: Duplicate
  • OS: generic,windows_xp
  • CPU: generic,x86
  • Submitted: 2006-10-30
  • Updated: 2011-02-16
  • Resolved: 2008-01-09
Related Reports
Duplicate :  
Duplicate :  
Duplicate :  
Relates :  
Relates :  
Description
A DESCRIPTION OF THE REQUEST :
As an example I suggest that the following should be possible:

(class String)
public String replace(String regex, String replaceFunc(int pos, int len, String match)) {
  ...
  String replacement = replaceFunc(...);
}

One would then be able to define callback functions "on the fly", e.g.
String y = x.replace("\\W", String myReplace1(int pos, int len, String match) {
  if (!match.equals(" ")) return "." else return "_";
});

[myReplace1 would in this case be an additional method of the "this" object] Alternatively, method definitions could be anonymous, such as:
String y = x.replace("\\W", String (int pos, int len, String match) {
...
});

Or, one could pass in predefined functions of this or another object; these methods might also be static (?):

(class Other)
  static String myReplace(int pos, int len, String match) {
    if (!match.equals(" ")) return "." else return "_";
  }
...
String y = x.replace("\\W", Other.myReplace);

Or, one could pass in instances of the Method class obtained via reflection; type safety must then be checked at runtime:

Method replace = ...;
String y = x.replace("\\W", replace);

As a matter of fact, these method parameters should support generics.

JUSTIFICATION :
This would be an important step towards functional programming.
I don't know if this would raise extremely difficult problems. For now it seems pretty straightforward except maybe for the reflection thing. Of course, the reflection API would have to be extended.
Maybe this can serve as a basis for discussion.

Comments
EVALUATION This is really a request for function objects and/or full-blown closures.
14-11-2006