I am reading about dart and one think that confuses me is the the syntax for anonymous functions. Specifically, how do I specify the type of the returned value for such a function.
For example, consider the following:
var f = (int x) {return x + 1;};
In this instance, I am declaring that the type of the parameter x
is int
. How can I explicitly say that the function returns an int
? I understand that the compiler will probably figure that out using type inference, but I want to explicitly specify the type to prevent the possibility of returning a value of the wrong type when writing more complex functions.
An anonymous function is a function that is not stored in a program file, but is associated with a variable whose data type is function_handle . Anonymous functions can accept multiple inputs and return one output. They can contain only a single executable statement.
To define the return type for the function, we have to use the ':' symbol just after the parameter of the function and before the body of the function in TypeScript. The function body's return value should match with the function return type; otherwise, we will have a compile-time error in our code.
Anonymous methods provide a technique to pass a code block as a delegate parameter. Anonymous methods are the methods without a name, just the body. You need not specify the return type in an anonymous method; it is inferred from the return statement inside the method body.
You can do something like this:
int Function(int x) f = (int x) {return 1 + x;}; String Function(String x, String y) concatenate = (String x, String y) {return '$x$y';};
EDIT: Here is a simpler way using type casting:
int f = (int x) {return x + 1;} as int;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With