1

I am new to JavaScript and have some intermediate knowledge of Java, after a few exercise, I am left with a puzzling question is there a way to apply the concept of anonymous functions in Java? is it even possible? I am well aware of the criticism I might receive for asking this question but I am asking anyway. An example of JavaScript anonymous function is below.

var myResult = (function () {
            return arguments[0] + arguments[1];
    }) (1,2);
alert(myResult);
3
  • 1
    docs.oracle.com/javase/tutorial/java/javaOO/… Commented Feb 17, 2017 at 0:47
  • Removed the javascript tag since this question isn't really about javascript. Commented Feb 17, 2017 at 4:42
  • This is where you got it wrong. The question refers to 2 languages here. There's no reason to remove the JavaScript tag. Because the code included is itself a JavaScript code Commented Feb 17, 2017 at 4:45

2 Answers 2

1

Anonymous inner classes do exactly that. A function cannot exist on its own in Java; it has to be wrapped in a class. So, the closest thing to an anonymous function is an anonymous inner class.

int myResult = (new Object() {
public int calc(int[] args){
        return args[0] + args[1];
    } }).calc( new int[]{ 1, 2} );
System.out.println(myResult);

This can now be easily done using Java 8 using lambda expressions (with functional interfaces).

Sign up to request clarification or add additional context in comments.

Comments

1

Using @FunctionalInterface Java 8

public class Test {
    @FunctionalInterface
        public interface Func {
        public String concat(String a, String b);
    }

    public static void main(String[] args) {
        Func func = (a, b) -> a + b;
        System.out.print(func.concat("Hello ", "World!"));
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.