Skip to content

Callback function equivalence (JavaScript vs Java)

In the context of Java 8 and modern JavaScript development, a specific equivalence exists between callback functions in JavaScript and Lambda expressions (utilizing Functional Interfaces) in Java^[600-developer__java__java8__java8-lambda.md]. This concept allows developers to pass logic or behavior as arguments to other functions, often described as "passing actions" or "passing methods"^[600-developer__java__java8__java8-lambda.md].

JavaScript Callbacks

In JavaScript, a callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action^[600-developer__java__java8__java8-lambda.md].

function javascriptCallback (a , callback){
    if(callback){
        callback();
    }
}

Java Lambdas (Functional Interfaces)

Prior to Java 8, passing methods (callbacks) was verbose. With the introduction of Lambda expressions and Functional Interfaces, Java achieves a similar functionality^[600-developer__java__java8__java8-lambda.md].

Common functional interfaces include: * Function: A unary function from T to R^[600-developer__java__java8__java8-lambda.md]. * Consumer: A unary function from T to void^[600-developer__java__java8__java8-lambda.md]. * Predicate: A unary function from T to boolean^[600-developer__java__java8__java8-lambda.md]. * Supplier: A nilary function to R^[600-developer__java__java8__java8-lambda.md].

Comparison Example

The following example contrasts the JavaScript style with the Java Lambda style using the Function interface (which accepts a parameter and returns a value)^[600-developer__java__java8__java8-lambda.md].

// Interface Function<Parameter, ReturnValue>
public Integer javaLamdba(Integer a , java.util.Function<Integer,Integer> fun) {
    return fun.apply(a);
}

// Usage: passing different logic blocks
Integer intReturnValue = javaLamdba(2, param -> param * param);
Integer intReturnValue = javaLamdba(2, param -> param + param);

Sources

  • 600-developer__java__java8__java8-lambda.md