Reputation: 442
I am trying to build a class to making some operations in mathematical sequences in Dart . And I am expecting a sequence as a lambda expression or function . I got confused when I try to build constructor of class . What should I write for parameters and data types ?
Sample lambda expression :
int sequence(int n) => 7+5*(n-1);
Sample function :
int fib(int n) {
if ((n == 1) || (n == 2)) {
return 1;
} else {
return fib(n - 1) + fib(n - 2);
}
}
How can I give that lambda expression and function as a parameter to another function ?
Upvotes: 1
Views: 3339
Reputation: 31219
So the type of your two methods are int Function(int)
which means it takes one int
as a parameter and outputs a int
.
There are basically two ways to do it. One is to explicit type that type as a parameter type like:
int sequence(int n) => 7 + 5 * (n - 1);
int generate1(int Function(int) function, int input) => function(input);
void main() {
print(generate1(sequence, 5)); // 27
}
Another way is to define a typedef
which will be a shorthand for your type:
int fib(int n) {
if ((n == 1) || (n == 2)) {
return 1;
} else {
return fib(n - 1) + fib(n - 2);
}
}
typedef SomeFunction = int Function(int n);
int generate2(SomeFunction function, int input) => function(input);
void main() {
print(generate2(fib, 5)); // 5
}
The typedef
can be easier if you have more complicated types you are reusing for multiple methods.
Upvotes: 4