Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

callback vs lambda in Java

Spring bean lifecycle documentation often mention callback methods.

While trying to find the meaning of callback, I came through few links that mention it is passing of one function as an argument to another, which could be achieved through interfaces in Java.

I am confused, if this is callback then what are lambda expression and functional interfaces ? Are they same or different?

like image 343
sss Avatar asked Sep 14 '18 07:09

sss


2 Answers

Lambda expressions are one of several ways to implement functional interfaces.

Functional interfaces are used as callbacks, but not all callbacks are functional interfaces. Interfaces used as callbacks can have multiple abstract methods, while functional interfaces can only have a single abstract method.

like image 37
Eran Avatar answered Oct 05 '22 11:10

Eran


Callback is a pattern where you pass a function somewhere and it gets called later.

Functional interfaces are a way of specifying what kind of function you expect.

A lambda is a quick way of implementing a functional interface. Lambdas are useful if you want to use callbacks.


For example:

Suppose I am going to generate a message at some point in the future, and you want to be told when it happens. I have a method that lets you give me a function to call when the message is ready.

public void callThisWithMessage(Consumer<String> messageConsumer);

You give me a message consumer, and I will call it later when the message is ready. This is an example of a callback.

The type of function you can give to me here is specified by the Consumer interface, which is a functional interface. This particular functional interface says that it has a method that accepts a parameter (in this case a string).

If you want to use my callback service, you can implement a consumer using a lambda function.

callThisWithMessage(msg -> System.out.println("Message received: "+msg));

This creates a lambda function that implements the functional interface Consumer<String>, and passes that to my method for subsequent callback.

like image 55
khelwood Avatar answered Oct 05 '22 11:10

khelwood