为什么在从具有泛型 (Int) return 类型的函数中 returning Dynamic (String) 时,Haxe 编译器不报错?

Why doesn't the Haxe compiler complain when returning a Dynamic (String) from a function with a generic (Int) return type?

我想知道为什么以下 Haxe 代码可以编译:

class Test<T> { // 1
    var l:List<Dynamic> = new List<Dynamic>(); // 2
    public function new() {} // 3
    public function add(d:Dynamic):Void { l.add(d); } // 4
    public function get():T { return l.pop(); }  // 5
    public static function main() { // 6
        var t:Test<Int> = new Test<Int>(); // 7
        t.add("-"); // 8
        trace(t.get());  // 9
    } // 10
}

我看到的编译问题:

如第 1 行所示,此 class 具有类型参数 T。在第 7 行中,指定 T 是一个 Int。所以 get() 函数(第 5 行)应该只有 return 和 Int。然而 - 神奇地 - 这个函数 returns a String (line 9).

所以...为什么编译器不抱怨这个?

A dynamic value can be assigned to anything; and anything can be assigned to it.

根据 Haxe 手册:https://haxe.org/manual/types-dynamic.html

由于 lList<Dynamic>l.pop() 的结果也将是 Dynamic。当它在 get().

中返回时,它将被隐式转换为 Int

我认为追踪 line 9 处的值时的运行时行为将取决于 Haxe 目标。

如果您将 l 更改为 List<T> 并使 add() 接受类型 T 的参数,那么编译器会报错。试试这个:https://try.haxe.org/#11327

class Test<T> { // 1
    var l:List<T> = new List<T>(); // 2
    public function new() {} // 3
    public function add(d:T):Void { l.add(d); } // 4
    public function get():T { return l.pop(); }  // 5
    public static function main() { // 6
        var t:Test<Int> = new Test<Int>(); // 7
        t.add("-"); // 8 - this won't compile anymore
        trace(t.get());  // 9
    } // 10
}