- Proposal: HXP-0015
- Author: YellowAfterlife
- Status: to be implemented
Provide syntax for defining static variables within the scope of a specific field.
Sometimes you want to reuse a static variable within a singular method - perhaps it is a data structure that you want to reuse an array/buffer so that you allocate the final returned structure "just right", or a native function reference that you resolve once on startup or even just depth for a recursive toString() call. Rest assured, it has to be static. And private. Not to be touched by anything else.
Currently most developers (and the standard library) take the approach of naming it something like __<method>_<var>
,
but there's a limited amount of convenience in doing so, especially as functions grow longer and going back and forth between variable declarations/use location requires utilizing bookmarks to maintain efficiency.
Suppose we were to recreate HX-JS $bind function in Haxe code,
public static function bind(o:Dynamic, m:Dynamic) {
if (m == null) return null;
static var closureID = 0;
if (m.__id__ == null) m.__id__ = closureID++;
// ... other code
}
this would compile as if it were
static var __bind_closureID = 0;
public static function bind(o:Dynamic, m:Dynamic) {
if (m == null) return null;
if (m.__id__ == null) m.__id__ = __bind_closureID++;
// ... other code
}
Accessing local variables of containing method in initializer expression should be forbidden,
public static function some(i:Int) {
static var trouble = i; // <- illegal
static var trouble2 = function() return ++i; // <- also illegal
}
Like with normal statics, either a value or an explicit type would be needed for the static variable.
Simulating block scoping
public static function some() {
// ...
if (condition) {
static var one = 1;
}
return one; // <- ilegal
}
would be consistent with local variables and preferred for situations where a variable is only really needed within a specific branch.
Currently static
keyword is entirely forbidden inside method bodies so there should be no impact.
As an old saying goes, most syntactic omissions can be corrected with a macro, and this is no exception, but it would be preferred to not have to iterate the expression tree build-time (as practice shows, this slowly adds up).
Still, an example of such a macro (implementing @:static var
) can be found here.
Similarly allowing local static function
could be handy for platforms where there is a cost to creating/invoking closures.