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:
public interface Hasher {
int getHash(String s);
}
public class HashFunction {
private Hasher f;
public HashFunction(Hasher f) {
this.f=f;
}
public Integer hash(String s){
return f(s);
}
}
then to use:
new HashFunction(new Hasher() {
public int getHash(String s) {return s.charAt(0)+0;}
});
Passing functions as parameters is not possible in Java, unless they added it in a recent language change.
The Java pattern is to use so-called anonymous classes, which implement a member method which has the desired behavior.
For example, see:
http://docstore.mik.ua/orelly/java-ent/jnut/ch03_12.htm
or
How are Anonymous (inner) classes used in Java?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With