Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Closure and Callbacks

Tags:

java

closures

Is there any other way in java to implement call backs apart from inner classes? What is the difference between callbacks and closures?

like image 911
Neeraj Avatar asked Mar 18 '10 09:03

Neeraj


People also ask

Is a closure the same as a callback?

a callback is executable code that is passed as an argument to other code. a closure is a function that is evaluated in an environment containing one or more bound variables. When called, the function can access these variables.

Is callback an example of closure?

Callbacks are also closures as the passed function is executed inside other function just as if the callback were defined in the containing function.

What is a callback?

A callback is a function passed as an argument to another function. This technique allows a function to call another function. A callback function can run after another function has finished.

What is closure with example?

A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). In other words, a closure gives you access to an outer function's scope from an inner function.


2 Answers

Closure is how you build it, callback is how you use it.

A callback can be implemented as a closure (in languages that have them) or an implementation of an interface (in Java, as an anonymous inner class or a regular class).

Callback means that you pass a piece of code to a function, so that the function can call that piece of code later. It is a special kind of parameter.

The piece of code can be a function pointer or a closure or an object with well-known methods, depending on what the language offers.

like image 171
Thilo Avatar answered Nov 03 '22 18:11

Thilo


Both closures and anonymous inner classes (and others) can be used as callbacks. A callback is just some code which is passed as an argument to other code.

A big difference of closures, compared to Java's anonymous inner classes, is that (in imperative languages) a closure can modify the variables of the surrounding scope. Wikipedia gives the following example:

var f, g;
function foo() {
  var x = 0;
  f = function() { return ++x; };
  g = function() { return --x; };
  x = 1;
  alert('inside foo, call to f(): ' + f()); // "2"
}
foo();
alert('call to g(): ' + g()); // "1"
alert('call to f(): ' + f()); // "2"
like image 34
Esko Luontola Avatar answered Nov 03 '22 18:11

Esko Luontola