当从具有泛型(Int)返回类型的函数返回Dynamic(String)时,为什么Haxe编译器不抱怨?

qua*_*ant 2 haxe

我想知道为什么下面的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
}
Run Code Online (Sandbox Code Playgroud)

我看到的编译问题:

如第1行所示,此类具有类型参数T.在第7行中,指定T为a Int.所以get()函数(第5行)应该只返回一个Int.但是 - 神奇地 - 这个函数返回一个String(第9行).

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

Sam*_*ale 5

动态值可以分配给任何东西; 任何东西都可以分配给它.

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

既然l是一个List<Dynamic>,结果l.pop()也将是Dynamic.这将在Int返回时隐式转换为get().

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

如果您更改l为a 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
}
Run Code Online (Sandbox Code Playgroud)

  • "哈希"谁甚至这样做? (3认同)