callback vs lambda in Java

Sameer Sinha :

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?

khelwood :

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 by 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. The 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.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=112267&siteId=1