Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Passing a Function as a Parameter like in JavaScript? [duplicate]

Tags:

java

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?

like image 600
user1277170 Avatar asked May 07 '26 10:05

user1277170


2 Answers

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;}
});
like image 99
Bohemian Avatar answered May 10 '26 00:05

Bohemian


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?

like image 32
SAJ14SAJ Avatar answered May 10 '26 01:05

SAJ14SAJ



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!