What is the `using` keyword in Haxe?

1.1k views Asked by At

I often see people use the keyword using in their Haxe code. It seem to go after the import statements.

For example, I found this is a code snippet:

import haxe.macro.Context;
import haxe.macro.Expr;
import haxe.macro.Type;
using haxe.macro.Tools;
using Lambda;

What does it do and how does it work?

1

There are 1 answers

2
Mark Knol On BEST ANSWER

The "using" mixin feature of Haxe is also referred as "static extension". It's a great syntactic sugar feature of Haxe; they can have a positive effect on code readability.

A static extension allows pseudo-extending existing types without modifying their source. In Haxe this is achieved by declaring a static method with a first argument of the extending type and then bringing the defining class into context through the using keyword.

Take a look at this example:

using Test.StringUtil;

class Test {
    static public function main() {
        // now possible with because of the `using`
        trace("Haxe is great".getWordCount());

        // otherwise you had to type
        // trace(StringUtil.getWordCount("Haxe is great"));
    }
}

class StringUtil {
    public static inline function getWordCount(value:String) {
        return value.split(" ").length;
    }
}

Run this example here: http://try.haxe.org/#C96B7

More in the Haxe Documentation: