The equal, equal operator in HaXe

The “==” operator to check object equality is implemented differently in the various programming languages. For example in Java, the “==” operator checks only the reference and you need the “equals”-Method in order to check the equality of objects:

String s1 = "foo";
String s2 = "foo";
System.out.println("" + (s1 == s2)); // will return false
System.out.println("" + (s1.equals(s2))); // will return true

In other languages like PHP, the “==”-operator can behave even more … strange …:

$a = "3.14159265358979326666666666";
$b = "3.14159265358979323846264338";
echo "" . ($a == $b); // will be 1 == true

So how is the “==”-operator defined in HaXe that can be cross-compiled into multiple languages including PHP and Java?

Well within Haxe, basic types like Int, Float, Strings and Bools are compared by values. So:

class Test {
    static function main() {
        var c1:String = "Hello";
        var c2:String = "World";
        trace(c1 == c2);  // will return false
        var c1:String = "Hello";
        var c2:String = "Hello";
        trace(c1 == c2);  // will return true
    }
}

However nob basic types are compared by-reference:

class C { public function new() {} }

class Test {
    static function main() {
        var c1:C = null;
        var c2:C = null;
        trace(c1 == c2); // will return true
        var c1:C = new C();
        var c2:C = new C();
        trace(c1 == c2); // will return false
    }
}