Welcome back to an exciting journey into the world of Java! Today's itinerary includes "Function Chaining," the practice of calling a function within another and handling multiple return values using Java's List
class. Picture nested matryoshka dolls and a multi-handled briefcase, and you'll grasp the concepts!
Let's demystify "Function Chaining". Have you ever prepared a cup of coffee? You sequentially boil water, brew coffee, and add cream. Now, imagine these steps as functions: doubleNumber()
and addFive()
. If we chain these functions together, we have our doubleAndAddFive()
function — an apt illustration of function chaining!
Take a look:
In doubleAndAddFive()
, doubleNumber()
is called first, and then its result fuels addFive()
. That's function chaining!
Now, let's dip our toes into function chaining. Consider the task of finding the square root of the sum of two numbers. We call sum()
inside sqrtOfSum()
, feeding its result to sqrt()
.
Consider this scenario: a board game where throwDice()
simulates the throw of two dice and returns both results. But how do you return both values from the function? This is where Java's List class saves the day!
You can just return a List
from the function, and it can handle any number of values in it. Let's see on example:
Here, we created an ArrayList
of two elements and provided it as a return value - easy and simple! You can access returned elements using the ArrayList::get
method after that.
Congratulations! You've delved into function chaining and learned how to handle multiple return values using the Pair
and the List
classes. Now, get ready for some fun practice exercises to reinforce your knowledge. Onwards, brave coder!
