Created
January 24, 2020 08:33
-
-
Save AlexVegner/96e13f69b657a02dfe61248fbcd5e7b6 to your computer and use it in GitHub Desktop.
dart_functions.dart
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| //import 'package:meta/meta.dart'; | |
| String f1() => 'value'; // For functions that contain just one expression, you can use a shorthand syntax | |
| String f2() { // this function equivalent to f1 | |
| return 'value'; | |
| } | |
| /// Functions as first-class objects | |
| /// You can pass a function as a parameter to another function. For example and return function | |
| void f3(Function f) { | |
| f(); | |
| } | |
| /// Fluction return function | |
| Function f4() { | |
| return f2; | |
| } | |
| // A function can have two types of parameters: required and optional. The required parameters are listed first, followed by any optional parameters. Optional parameters can be named or positional. | |
| /// a1 - positional required | |
| /// a2 - named optional | |
| int f5(int a1, {int a2 = 6}) { | |
| return a1 + a2; | |
| } | |
| /// a1 - positional required | |
| /// a2 - named required | |
| int f6(int a1, {/*@required*/ int a2 = 6}) { | |
| return a1 + a2; | |
| } | |
| /// a1 - positional required | |
| /// a2 - positional optional | |
| int f7(int a1, [int a2 = 6]) { | |
| return a1 + a2; | |
| } | |
| // define function type | |
| typedef Operation = int Function(int a, int b); | |
| int sum(int a, int b) => a + b; | |
| int operation(int a, int b, {Operation op = sum}) { | |
| return op(a, b); // execute function | |
| } | |
| void main() { // entry point | |
| final func = operation; // function variable | |
| final result = func(1, 2, op: (int a, int b) => a * b); // op - anonymous function | |
| print(result); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment