static var
and static final
declarations within a function create variables that are scoped to the function (they cannot be referred to from outside the function), but are only initialized once.
This can be used to implement a cache or memoization pattern for functions without creating too many class fields.
class Main { static function getData() { static var cache:Null<String> = null; if (cache == null) { cache = slowOperation(); } return cache; } static function slowOperation() { trace("performing slow operation..."); return "result"; } static public function main() { trace(getData()); // performing slow operation... result trace(getData()); // result } }
Similarly to static class variables, the initial value assigned to a local static variable (if any) must not refer to instance variables or arguments of the current function.