Search code examples
haxe

What's the reason behind "structure has extra field" error


Consider this code:

var t: {a: Int} = {a:100, b:200};

It does not compile with error: { b : Int, a : Int } has extra field b

But this code compiles fine:

class Foo {
    public var a: Int = 100;
    public var b: Int = 200;
    public function new() {}
}
...
var t: {a: Int} = new Foo();

Why is the first case forbidden?

What can go wrong if there are some extra fields? And if something can go wrong why they are allowed in second case.


Solution

  • This has previously been discussed in this issue, where Nicolas gives the following reasoning for the current behavior:

    The idea is that constant structures are not allowed to be reduced. This allows for instance to check for the following:

    function foo(o:{?x:Int,?y:Int}) {
    }
    var pt = { x: 0, yy : 1 }; // typo
    foo(pt); // goes unnoticed
    

    Also, it will gives error if you modify the signature of foo, for instance by removing a field.

    However, the issue is still open and it looks like the behavior might be changed to allow this in the future.