Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test if a Dart value is actually a function?

Is it possible to test if a value is a function that can be called? I can test for null easily but after that I have no idea how to ensure the parameter passed in is actually a function?

void myMethod(funcParam)
{
   if (funcParam != null)
   {
       /* How to test if funcParam is actually a function that can be called? */
       funcParam();
   }
}
like image 535
Phil Wright Avatar asked Dec 09 '22 08:12

Phil Wright


1 Answers

void myMethod(funcParam) {
    if(funcParam is Function) {
        funcParam();
    }
}

Of course, the call to funcParams() only works if the parameter list matches - is Function doesn't check for that. If there are parameters involved, one can use typedefs to ensure this.

typedef void MyExpectedFunction(int someInt, String someString);

void myMethod(MyExpectedFunction funcParam, int intParam, String stringParam) {
    if(funcParam is MyExpectedFunction) {
        funcParam(intParam, stringParam);
    }
}
like image 170
MarioP Avatar answered Jan 10 '23 18:01

MarioP