Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Return type of an anonymous function

Tags:

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.

like image 269
safsaf32 Avatar asked Aug 13 '18 15:08

safsaf32


People also ask

Do anonymous functions have return type?

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.

What is return type function in TypeScript?

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.

What are anonymous functions in C#?

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.


1 Answers

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; 
like image 101
Mattia Avatar answered Sep 21 '22 14:09

Mattia