Local functions are functions without a name. (often named "anonymous functions") They are values and as such can be assigned to any variable. The following is an example:
public class User { var sayHello : String->Void; public function new() { sayHello = function(to : String) { trace("Hello" + to); }; } }
Local functions can access any local variable declared in the same scope as static variables, but cannot access the this
variable.
Local functions are typed. The local function in the preceding example is typed as String-> Void
. A function that takes a String
, an Int
, and returns a String
would be typed as String ->Int -> String
.
So, continuing the previous example, one could call the function in the following way:
public class User { var sayHello : String->Void; public function new() { sayHello = function(to : String) { trace("Hello " + to); }; sayHello("World"); //Call the sayHello function. } }
Note that the sayHello
method could be called from another method, but only after the value of the sayHello
variable is set (that is, after assigning the function to the sayHello
variable); otherwise, trying to call a null value always results in a runtime error.
18.221.254.61