0

Shouldn't the following code throw an error instead of executing?

class Weird
{
    public static function main()
    {
        var weirdPerson = Type.createInstance(Person,[["What", "the", "?"]]);
        trace(weirdPerson.likesCake);
        // Outputs [What,the,?]

        var normalPerson = Type.createInstance(Person,[true]);
        trace(normalPerson.likesCake);
        // Outputs John Doe
    }
}


class Person
{
    public var likesCake:Bool;

    public function new(?likesCake:Bool=true)
    {
        this.likesCake = likesCake;
    }
}

The wrong type is being parsed to the constructor of the weirdPerson but its still being accepted. The Bool property 'likesCake' of the weirdPerson is actually assigned a String array!? Is there something wrong here or is this the expected functionality? Maybe the type of the likesCake property has changed at runtime from Bool to Array only for this instance of the Person class?

Gama11
  • 31,714
  • 9
  • 78
  • 100

1 Answers1

2

From the docs for Type.createInstance:

If cl or args are null, or if the number of elements in args does not match the expected number of constructor arguments, or if any argument has an invalid type, or if cl has no own constructor, the result is unspecified.

Basically, when you use reflection in Haxe (the Type and Reflect classes), the Haxe compiler can't promise to catch any type errors. In this case, the second argument to createInstance() is typed as Array<Dynamic> - it will accept an array with any types, and do no checks whatsoever.

On Dynamic platforms, like Javascript or Neko, they will probably let you get away with this, and you run into the sort of errors like you're seeing. On static platforms (C++, Java, Flash?) the underlying platform might reject this at runtime. Because Haxe doesn't make any guarantees between platforms, it is called "unspecified" and you should be careful with your arguments.

These "Dynamic" reflection arguments can cause very frustrating bugs that are untraceable to the Haxe compiler, so be careful whenever using these functions... (I spent 2 hours before tracking one down yesterday!)

Jason O'Neil
  • 5,908
  • 2
  • 27
  • 26
  • +1. Avoid reflection like the plague. It causes hard to track bugs - particularly in conjunction with dead code elimination. – back2dos Jul 29 '14 at 09:17