Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing a function as a parameter in Haxe

Tags:

haxe

In the Haxe programming language, is it possible to pass a function as a parameter (like in JavaScript?)

For example, is the following code considered valid in Haxe?

function a(){
    trace("This function is being used as a parameter!");
}

function b(theFunction){
    theFunction();
}

b(a); //is this equivalent to a(); ?
like image 815
Anderson Green Avatar asked Dec 24 '12 21:12

Anderson Green


2 Answers

It is definitely possible, and is a pattern used in the standard library, especially in the Lambda class:

class Test {
  static function main(){
    var arr = [0,1,2,3,4,5,6,7,8,9,10];
    var newArr = Lambda.filter(arr, function (num) { 
      return num % 2 == 0; 
    });
    for (i in newArr)
    {
      trace (i);
    }
  }
}

(See http://try.haxe.org/#C9dF3)

To define your own methods that take functions as parameters you use the (param1Type)->(param2Type)->(returnType) syntax:

function test1(myFn:String->Void) { myFn("hi"); }
test1(function (str) { trace(str); });

function test2(myFn:String->String) { var newStr = myFn("hi"); }
test2(function (str) { return str.toUpperCase(); });

function test3(myFn:Int->String->Array<Int>->Void) { myFn(3, "Jason", [1,2,3,4]); }
test3(function(num:Int, name:String, items:Array<Int>) { ... });
like image 161
Jason O'Neil Avatar answered Sep 25 '22 18:09

Jason O'Neil


See and try for yourself please:)

http://try.haxe.org/#CFBb3

like image 22
Andy Li Avatar answered Sep 25 '22 18:09

Andy Li