Phil Wright
Phil Wright

Reputation: 22926

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

Upvotes: 5

Views: 1325

Answers (3)

lrn
lrn

Reputation: 71723

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.

Upvotes: 4

MarioP
MarioP

Reputation: 3832

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

Upvotes: 7

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657546

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

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

Upvotes: 3

Related Questions