You are on page 1of 8

Functions

function is a set of codes that together perform a specific task. It is used to


break the large code into smaller modules and reuse it when needed.
Functions make the program more readable and easy to debug. It improves the
modular approach and enhances the code reusability. The function provides
the flexibility to run a code several times with different values. A function can
be called anytime as its parameter and returns some value to where it called.
Advantages of Functions
• It increases the module approach to solve the problems.
• It enhances the re-usability of the program.
• We can do the coupling of the programs.
• It optimizes the code.
• It makes debugging easier.
• It makes development easy and creates less complexity.
Defining a Function
A function can be defined by providing the name of the function with the
appropriate parameter and return type. A function contains a set of
statements which are called function body. The syntax is given below.

return_type func_name (parameter_list):


{
//statement(s)
return value;
}
• return_type - It can be any data type such as void, integer, float, etc. The
return type must be matched with the returned value of the function.
• func_name - It should be an appropriate and valid identifier.
• parameter_list - It denotes the list of the parameters, which is necessary
when we called a function.
• return value - A function returns a value after complete its execution.
Calling a Function
After creating a function, we can call or invoke the defined function inside the
main() function body. A function is invoked simply by its name with a
parameter list, if any. The syntax is given below.
fun_name(<argument_list>);
or
variable = function_name(argument);

When we call a function, the control is transferred to the called function. Then
the called function executes all defined statements and returns the result to
the calling function. The control returns to the main() function.
Example:
mul(10,20);

Passing Arguments to Function


When a function is called, it may have some information as per the function
prototype is known as a parameter (argument). The number of parameters
passed and data type while the function call must be matched with the
number of parameters during function declaration. Otherwise, it will throw an
error. Parameter passing is also optional, which means it is not compulsory to
pass during function declaration. The parameter can be two types.
Actual Parameter - A parameter which is passed during a function definition is
called the actual parameter.
Formal Parameter - A parameter which is passed during a function call is called
the formal parameter.
Return a Value from Function
A function always returns some value as a result to the point where it is called.
The return keyword is used to return a value. The return statement is optional.
A function can have only one return statement.
void main() {
print("Example of add two number using the function");
// Creating a Function
int sum(int a, int b) {
// function Body
int result;
result = a + b;
return result;
}

// We are calling a function and storing a result in variable c


var c = sum(30, 20);
print("The sum of two numbers is: ${c}");
}

Anonymous Function
We have learned the Dart Function, which is defined by using a user-define
name. Dart also provides the facility to specify a nameless function or function
without a name. This type of function is known as an anonymous function,
lambda, or closure. An anonymous function behaves the same as a regular
function, but it does not have a name with it. It can have zero or any number
of arguments with an optional type annotation.
We can assign the anonymous function to a variable, and then we can retrieve
or access the value of the closure based on our requirement.
An Anonymous function contains an independent block of the code, and that
can be passed around in our code as function parameters.
Syntax:

(parameter_list) {
statement(s)
}
Example:
void main() {
var list = ["James", "Patrick", "Mathew", "Tom"];
print("Example of anonymous function");
list.forEach((item) {
print('${list.indexOf(item)}: $item');
});
}

In the above example, we defined an anonymous function with an untype


argument item. The function called for each item in the list and printed the
strings with its specified index value.
Lambda Function in Dart:
They are the short way of representing a function in Dart. They are also called
arrow function. But you should note that with lambda function you can return
// Lambda function in Dart
void function1() => print("Welcome to Fortune");
void square(int x) => print("Square of ${x} is ${x * x}");
void main() {
function1(); // Calling Lambda function
square(5);
}

Nested Functions
void main() {
print("Main");
myFunction();
}

void myFunction() {
print("MyFunction");

void nestedFunction() {
print("NestedFunction");
}

nestedFunction();
}
Functions with Optional Parameter:
There are also optional parameter system in Dart which allows user to give
some optional parameters inside the function.

Sr.
No. Parameter Description

Optional Positional
1. Parameter To specify it use square (‘[ ]’) brackets

When we pass this parameter it is menditory to


Optional Named pass it while passing values. It is specify by
2. parameter curly(‘{ }’) brackets.

Optional parameter
3. with default values Here parameters are assign with default values.

Optional Positional Parameter


Example:
void main() {
print("Dart Optional Positional Parameter.");
function1(12);
function1(123, 21);
}

function1(p1, [o1]) {
print("Param Value Is : ${p1} and Option Param Valus Is : ${o1}");
}

Optional Named Parameter


Calling a function having optional named parameters, the individual
parameter’s name must be specified while the value is being passed. Names
are specified using parameter:value. The sequence of passing the parameter(s)
does not matter.
Example:
void main() {
print("Dart Optional Named Parameter.");
function1(12);
function1(123, np1: 10);
function1(123, np2: 20);
function1(123, np1: 10, np2: 20);
}

function1(p1, {np1, np2}) {


print("Param Value Is : ${p1}");
print("Named Param 1 Valus Is : ${np1}");
print("Named Param 2 Valus Is : ${np2}");
}

Optional Parameters with Default Values


Example:
void function1(int g1, {int g2: 12}) {
// Creating function 1
print("g1 is $g1");
print("g2 is $g2");
}

void main() {
function1(4);
function1(5, g2: 9);
}

Recursive Function
A recursive function is not much different from any other function, basically a
function calling itself directly or indirectly is known as recursive function. A
recursive function repeats itself several times, in order to compute or return
final output. Recursive functions are quite common in computer programing as
they allow programmers to write efficient programs with minimal code.
Characteristics of a Recursive function
• A recursive function is a function which calls itself.
• The speed of a recursive program is slower because of stack overheads.
• A recursive function must have terminating conditions or base case, and
recursive expressions.
Example:
int fact(int n) {
if (n > 1)
return n * fact(n - 1);
else
return 1;
}

main() {
var num = 5;
var f = fact(num);
print("Factorial Program Using Recursion.");
print("Factorial of 5 Is : ${f}");
}

Function as Function Parameters


Step 1: Define a method that takes a function parameter
Step 2: Create one or more functions to pass into that function parameter
Step 3: Pass the functions into the method
Example:
// 1 - define a method that takes a function
void exec(int i, Function f) {
print(f(i));
}

// 2 - define a function to pass in


int plusOne(int i) => i + 1;
int double(int i) => i * i;

void main() {
// 3 - pass the functions into the method
exec(10, plusOne);
exec(10, double);
}

You can also pass lambda expressions into function parameters


Note that in addition to passing functions into functions, you can also pass
lambda expressions into methods that have function parameters. These two
examples also print out 11 and 100:

// 4 - note that you can also pass in lambda expressions


exec(10, (x) => x + 1); //plusOne
exec(10, (x) => x * x); //double

Example:
// 1 - define a method that takes a function
void exec(int i, Function f) {
print(f(i));
}

void main() {
// 3 - pass the functions into the method
exec(10, (x) => x + 1);
exec(10, (x) => x * x);
}

You might also like