"using" mixin

It is often the case that there is some code in which you might want to add some additional methods to suit your specific needs. And often you can't. For instance if the code is the standard library or a 3rd party library, or if your additional code is too much specific and would not fit into the existing codebase, etc.

In some cases you can simply inherit the existing class to add your code, but in some other cases - for instance when you don't control the way instances are created - you cannot. Also, if you have several developers, each having its own subclass, this simply does not work well.

In all these cases, the "using" mixin feature of Haxe will help you, since it allows you to extend an existing code without modifying it.

"using" example

Most of the time, you will end up anyway writing a set of static "helper methods" that follow this pattern :

class StringHelp {
    public static function startsWith( s : String, sub : String ) { .... }
    public static function isSpace( s : String, ?pos : Int ) { .... }
}

Then your code will often looks like :

function isHello( s : String ) {
    return StringHelp.startsWith(s,"hello") && StringHelp.isSpace(s,6);
}

With using, you can simply rewrite your code as the following :

// at the top of your file, together with imports
using StringHelp;
// ...
function isHello( s : String ) {
    return s.startsWith("hello") && s.isSpace(6);
}

The runtime result will be exactly the same that if you have wrote static calls to the StringHelp class, but it actually looks and feels like you're using additional String methods.

When a field is not found, using will simply perform a lookup into the static methods of the classes you're currently using and try to find one that match the current type.

Using "using Lambda" with arrays and lists


It may confuse new Haxe users that array and list classes don't have map() and filter() functions. However, these functions are a part of the Lambda class, and adding "using Lambda;" to the class implementation, the arrays and lists are easily armed with these functions. You can find more information on this subject here.

Using "using" with basic types, functions and enums


Please note that using also works for types which are not objects or classes instances, for instance basic types, functions or enums :
// MyEnum.hx
enum MyEnum {
    A;
    B;
    C;
}
class MyEnumHelper {
    public static function toInt( e : MyEnum ) {
        return Type.enumIndex(e);
    }
}

// Test.hx
using MyEnum;
class Test {
    public static function main() {
        trace( C.toInt() ); // 2 !
    }
}

version #15422, modified 2012-09-01 23:34:19 by jan_flanders