Algobook
- The developer's handbook
mode-switch
back-button
Buy Me A Coffee
Wed Dec 20 2023

How to pass in a callback function as an argument

In this guide, we will show how we can create a method that accepts a function as an argument and call it as a callback. This is very handy when we e.g have a generic method, that performs some logic, and we then want the result be passed into another function.

Example

To keep it very simple, we will create a method that will accept two numbers, and then depending on what we want to do, we will simply let our method pass along the numbers into a callback that will handle the logic.

So, let's start by creating our function, that we will call calculation.

public static int calculation(int a, int b, CalculationExecutor fn) { return fn.calc(a, b); }

Our function accepts two integers, and then a callback function that we can execute with our numbers.

Then, we will create an interface that we will call CalculationExecutor that will have a method called calc. Since our previous method accepts two integers and that the function should return an integer as well, we need to specify that in our interface.

interface CalculationExecutor { int calc(int a, int b); }

Then, when we call our calculation method, we will simply provide the calculation with a callback with our own logic that suits our needs. Notice that we are always passing in a and b in the callback and that it returns an integer, as we specified in the interface.

public static void main(String[] args) { int addedNumbers = calculation(1, 2, Integer::sum); int subtractedNumbers = calculation(1, 2, (a, b) -> a - b); int multipliedNumbers = calculation(1, 2, (a, b) -> a * b); System.out.println(addedNumbers); // 3 System.out.println(subtractedNumbers); // -1 System.out.println(multipliedNumbers); // 2 }

In above example, we called the same function, calculation, but with some different callback methods. This was a very simple example, but I just wanted to demonstrate how this can be done.

Summary

In this short guide, we showed how to use functional interfaces to utilize the power of callback methods. This allows us to be very flexible in our coding, and to write generic functions that can have different side effects depending on use cases.

I hope you found this short tutorial helpful, and that it could help you with keeping your code more nice and tidy.

signatureWed Dec 20 2023
See all our articles