Exploring Functions in Dart: Invocation and Default Parameters
Introduction and Overview
Welcome back! Today's mission will expose us to the world of Dart, where we'll concentrate on working with functions, invoking stand-alone functions within other functions, and using default argument values.
In Dart we can also incorporate the results of different functions by calling them within a new function. If no value is passed, we will use default argument values for the corresponding parameters. Are you ready to get your hands dirty with Dart and functions? Let's dive in!
Understanding Function Invocation
In Dart, a function is activated or executed when we invoke or call it. Let's take an example of a function named greetUser. Invoking this function would look like: greetUser(). Here is an instance:
Invoking a function in Dart is similar to giving a command — by invoking the command, you produce the intended result!
Calling Independent Functions Inside a Function
Practically, we often need to merge the outputs of different functions. In such scenarios, invoking standalone functions within another function proves useful.
Consider that you have two separate functions, sayHello and sayGoodbye. If we want to create a new function greet that calls both these functions, it would look like this:
Voilà! By invoking sayHello and sayGoodbye within the greet function, both "Hello" and "Goodbye" are printed together.
Using Other Functions Results
While creating functions, we often require the output of one function in another. In those cases, we would invoke the required function within another function.
In this lesson, we also introduce the num data type, which in Dart is quite versatile, as it can hold both integer and floating-point values seamlessly. This capability is especially beneficial in functions that perform mathematical operations, as it automatically accommodates numbers with or without decimal points without the need for explicit type conversion between int and double. This flexibility makes num invaluable when working across various functions that require numerical computations.
Imagine that we have a function addNumbers to add two numbers and a function calculateAverage to calculate the average of two numbers. To perform the calculation, we first need to utilize addNumbers within calculateAverage. Here's how we accomplish this:
In our calculateAverage function, we invoke addNumbers, which returns the sum of num1 and num2, and we then use this sum to compute the average.
