Closures |
Top Previous Next |
Closures are supported in SmartMS with the same syntax as in Delphi.
You are allowed to use a named local procedure as a closure, with optional capture of local variables, allowing for neater layout of code.
The term closures is very frequently treated as a synonym for the term anonymous methods. Though closures are specific to anonymous methods, they are not the same concept. Anonymous methods are possible without closures. Do not use the terms interchangeably. Anonymous methods have some considerations for variable scope.
In traditional Pascal, anything in a var block which exists physically above the code which references is visible, are called nested methods, for example:
SmartMS nested routine example.
Code example: Using nested methods
upper string lower string inner string upper string -------------------------
The method InnerMethod only lives in one place and is not visible anywhere except in the OuterMethod body. The variable lowerScope is not visible in the InnerMethod, so we can not have direct access to this variable in the InnerMethod, this variable is not in the scope of the method InnerMethod. To accomplish this, we can use closures.
Code example: Using Closure with SmartMS
myObj.DoStuff; //j is available because it is wrapped in a closure! 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ------------------------------------------------
Using closures, we can have direct access to j counter from with the anonymous method without using a parameter. SmartMS will place j in the scope of the method and make it available to us without any work on our part.
Note: you can not have a for loop which uses a counter which exists in the closure (the counter must be local).
myObj.DoStuff2; //you can have for loop because the counter j is declared as local! 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ----------------------
Result in Closures
The Result value can live in a closure in SmartMS. For example:
WriteLn( myObj.AddDays(10) );
8/19/2014 19:09 = TODAY 8/29/2014 22:09 = 41880.92333288195 -----------------------------------
WriteLn( myObj.AddDays2(10) );
8/19/2014 19:09 = TODAY 8/29/2014 22:09 = 41880.92333288195 ----------------------------------- Note that you can use a variable to reference the return value in outer scope, hence it requires closure.
More details see Anonymous methods |