📅  最后修改于: 2020-11-05 04:20:20             🧑  作者: Mango
功能是可读,可维护和可重用代码的构建块。函数是执行特定任务的一组语句。函数将程序组织成逻辑代码块。一旦定义,可以调用函数来访问代码。这使代码可重用。此外,功能使读取和维护程序代码变得容易。
函数声明告诉编译器函数的名称,返回类型和参数。函数定义提供了函数的实际身体。
Sr.No | Functions & Description |
---|---|
1 | Defining a Function
A function definition specifies what and how a specific task would be done. |
2 | Calling a Function
A function must be called so as to execute it. |
3 | Returning Functions
Functions may also return value along with control, back to the caller. |
4 | Parameterized Function
Parameters are a mechanism to pass values to functions. |
当不需要为执行函数强制传递参数时,可以使用可选参数。通过在参数名称后附加问号,可以将参数标记为可选。可选的参数应该被设置为一个函数的最后一个参数。
我们在Dart中有三种类型的可选参数-
Sr.No | Parameter & Description |
---|---|
1 |
Optional Positional Parameter
To specify optional positional parameters, use square [] brackets. |
2 |
Optional named parameter
Unlike positional parameters, the parameter’s name must be specified while the value is being passed. Curly brace {} can be used to specify optional named parameters. |
3 |
Optional Parameters with Default Values
Function parameters can also be assigned values by default. However, such parameters can also be explicitly passed values. |
递归是一种迭代操作的技术,方法是反复对自身进行函数调用,直到获得结果为止。当您需要在循环中使用不同的参数重复调用同一函数时,最好使用递归。
void main() {
print(factorial(6));
}
factorial(number) {
if (number <= 0) {
// termination case
return 1;
} else {
return (number * factorial(number - 1));
// function invokes itself
}
}
它应该产生以下输出–
720
Lambda函数是表示函数的简洁机制。这些功能也称为箭头功能。
[return_type]function_name(parameters)=>expression;
void main() {
printMsg();
print(test());
}
printMsg()=>
print("hello");
int test()=>123;
// returning function
它应该产生以下输出–
hello 123