Test if a Dart value is actually a function?

2019-07-03 23:24发布

问题:

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();
   }
}

回答1:

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);
    }
}


回答2:

  var f = () {};
  print(f is Function); // 'true'

  var x = (x){};
  print(x is Function); // 'true'


回答3:

In your case, you want to check if the function can be called with zero arguments.

typedef NullaryFunction();

main () {
  var f = null;
  print(f is NullaryFunction);  // false
  f = () {};
  print(f is NullaryFunction);  // true
  f = (x) {};
  print(f is NullaryFunction);  // false
}

If you just want to know that it is some function, you can test with ... is Function. All callable objects implement Function, but it is technically possible (though often not useful) to implement Function manually without actually being callable. It does make a kind of sense for objects that mock callability through noSuchMethod.