Sometimes we come across a situation where the functionality of an already existing function is required in a new function. Instead of rewriting code, we can simply call the old function in the body of the new one we are writing. This will be made clear with an example.
Let’s write a function which gives the square of a given number.
1234567
def square(x: Double) ={
x * x
}
// Driver Code
val result = square(5)
print(result)
Run
Save
Reset
Now, we want to write a function which takes the sum of the squares of two numbers. Let’s try doing this using the square function we defined above.
123
def squareSum(x: Double, y: Double) ={
square(x) + square(y)
}
In the code above, we are calling the function square in the function SquareSum. Let’s call SquareSum and see what happens.