What is the `using` keyword in Haxe?
Asked Answered
W

1

7

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?

Williams answered 19/6, 2015 at 8:30 Comment(0)
W
17

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:

Williams answered 19/6, 2015 at 8:30 Comment(2)
Is it faster to use 'using' over 'import'?Venule
@Venule They are completely different thingFirmin

© 2022 - 2024 — McMap. All rights reserved.