Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a function which accepts a function with specific parameters as an argument?

I'd like to create a function which accepts a function that accepts specific types of parameters as an argument. For example:

myFn(Function paramFn) {
    paramFn([1, 2, 3]);
}

How can I ensure that paramFn accepts a List<int> as an only parameter?

like image 616
nopotato Avatar asked Feb 04 '26 00:02

nopotato


2 Answers

You can use typedef to define the signature you want like described in Kul's answer or you can simply inline the function signature in the parameter:

myFn(void paramFn(List<int> l)) {
  paramFn([1, 2, 3]);
}
like image 139
Alexandre Ardhuin Avatar answered Feb 06 '26 10:02

Alexandre Ardhuin


You can use typedef to associate a symbol with a function that satisfies the signature you want. Something like

typedef void ParamFn(List<int> l);

myFn(ParamFn f) {
  f('abc');   // compile time error
  f([1,2,3]); // works fine
}
like image 38
Kul Avatar answered Feb 06 '26 08:02

Kul



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!