How can I write an anonymous function in Java?

aarona picture aarona · May 3, 2010 · Viewed 123.7k times · Source

Is it even possible?

Answer

chris picture chris · May 3, 2010

if you mean an anonymous function, and are using a version of Java before Java 8, then in a word, no. (Read about lambda expressions if you use Java 8+)

However, you can implement an interface with a function like so :

Comparator<String> c = new Comparator<String>() {
    int compare(String s, String s2) { ... }
};

and you can use this with inner classes to get an almost-anonymous function :)