Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the `using` keyword in Haxe?

Tags:

using

haxe

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?

like image 436
Mark Knol Avatar asked Jun 19 '15 08:06

Mark Knol


1 Answers

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:

  • Haxe static extensions in the Haxe Manual
  • Haxe static extensions tagged articles in the Haxe Code Cookbook
like image 98
Mark Knol Avatar answered Sep 28 '22 06:09

Mark Knol