Lesson 2
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:

Dart
1// Creating the function (serves as a plan for now) 2void greetUser() { 3 print("Hello, user!"); 4} 5 6// Invoking the function (bringing the plan to reality) 7greetUser(); // Output: Hello, user!

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:

Dart
1// Defining the independent functions 2void sayHello() { 3 print("Hello!"); 4} 5 6void sayGoodbye() { 7 print("Goodbye!"); 8} 9 10// Invoking them inside another function 11void greet() { 12 sayHello(); 13 sayGoodbye(); 14} 15 16// Calling the combined function 17greet(); 18/* 19Prints: 20Hello! 21Goodbye! 22*/

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:

Dart
1// Define `addNumbers` function that returns the sum of two numbers 2num addNumbers(num num1, num num2) { 3 num sum = num1 + num2; 4 return sum; 5} 6 7// Define `calculateAverage` function 8num calculateAverage(num num1, num num2) { 9 // Invoke addNumbers inside calculateAverage 10 num sum = addNumbers(num1, num2); 11 num avg = sum / 2; 12 return avg; 13} 14 15// Test the function 16var average = calculateAverage(10, 20); // Output: 15

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.

Parameter Default Values

In Dart, functions can be designed to take both required and optional parameters, the latter of which can be assigned default values. This increases the flexibility of function calls by allowing you to specify a default behavior when no argument is provided for an optional parameter, while still enforcing the provision of arguments for required ones.

Here is a modified example that includes one required parameter and one optional parameter with a default value:

Dart
1// 'greeting' is a required parameter, while 'name' is optional with a default value of 'dart coder' 2void greetUser(String greeting, [String name = "dart coder"]) { 3 print('$greeting, $name!'); 4} 5 6// Invoke greetUser with only the required parameter 7greetUser('Welcome'); // Output: "Welcome, dart coder!" 8 9// Invoke greetUser with both the required parameter and a value for the optional parameter 10greetUser('Hello', "Alice"); // Output: "Hello, Alice!"

In this example the greetUser function necessitates a required greeting string (such as 'Welcome' or 'Hello') to be passed every time the function is called. The name parameter is optional but defaults to the string "dart coder" if no value is provided. This demonstrates the adaptability of functions in Dart to cater to different scenarios by balancing required inputs with the convenience of optional parameters with default values.

Enhancing Flexibility with Named Parameters

Diving deeper into Dart's functions, alongside default values for positional parameters, Dart introduces an elegant feature: named parameters with default values. Enclosed in curly braces {}, named parameters are optional and enhance the readability and flexibility of function calls, as they allow arguments to be passed in any order.

Consider this streamlined example:

Dart
1void greetUser({String greeting = "Hello", String name = "dart coder"}) { 2 print('$greeting, $name!'); 3} 4 5// Various ways to invoke the function 6greetUser(name: 'Alice', greeting: 'Welcome'); // Output: "Welcome, Alice!" 7greetUser(greeting: 'Good morning'); // Output: "Good morning, dart coder!" 8greetUser(); // Output: "Hello, dart coder!"

By making use of optional named parameters, Dart allows for highly readable and maintainable code even when functions have several parameters. This feature not only simplifies function definitions but also the function calls, enhancing both clarity and code organization.

Lesson Summary and Practice

Bravo! You've successfully understood how to invoke functions in Dart, how to call independent functions within another function, and how to use default argument values in Dart functions.

Get ready for the series of exercises lined up next to enhance your comprehension and coding abilities. Remember, practice is key to learning! As we continue our exciting journey in Dart, stay engaged, and maintain your enthusiasm! Stay tuned for more!

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.