I’m trying to write a function, so I can pass a function as a parameter, such as
public class HashFunction {
private Function f;
public HashFunction(Function f) {
this.f=f;
}
public Integer hash(String s){
return f(s);
}
}
So I can write code like
new HashFunction(function(String s){ return s.charAt(0)+0; });
Like in javascript.
How can I do this?
Unlike many other modern languages, currently java doesn’t syntactically support “floating chunks of code” (known as closures).
However, the concept may be achieved through the use of anonymous classes, which are “on the fly” implementation declarations that typically implement an interface, but can also extend a class.
Here’s how you would code your example in java:
then to use: