Dart Optional Default Parameters Function

0
64738
Dart default Parameters function
dart default parameter function example

Dart allows to assign default optional values to parameters in a function. Such a function is called Dart Optional Default Parameters Function.

To understand the concept of default parameters let’s take an example. The syntax of default parameters function will look like this

  
int findVolume(int length, int breadth, {int height = 12}) {
  return length*breadth*height;
}

In the above code height is the named parameter and in addition, a default value of 12 has been assigned as well. Let’s explore more by invoking this function.

  
var result = findVolume(3, 6);

Here 3 is the value of length and the value of breath is 6. Only two parameters have been passed. What about the 3rd parameter? Well the third parameter will use the default assigned value.

The syntax to override the default parameter value is

  
var result = findVolume(3, 6,height:15);

On execution the height 15 will replace the default value of height which is 12.

Dart Default Parameters Example

Time to complete a default parameter example.

  
void main() {
  var result = findVolume(3, 6);
  print(result);
  print("");
  //Overriding the default parameter
  var result2 = findVolume(3, 6, height: 15);
  print(result2);
}

int findVolume(int length, int breadth, {int height = 12}) {
  return length * breadth * height;
}

Launch the application and the output result is following

  
216

270

This is it. Do forget to learn about

We have the same concept in Kotlin. Check Kotlin named parameters.

LEAVE A REPLY

Please enter your comment!
Please enter your name here