编译时未检查可选参数 Haxe

Optional argument not checked at compile time Haxe

我今晚刚刚发现了 Haxe,我很高兴地惊讶于语法对开发人员的友好程度。易于理解,非常高兴它接近 ECMAScript。

.
└── src/
    ├── http/
    │   ├── Router.hx
    │   └── Route.hx
    └── Main.hx

我有一个路由器 class,它声明了一个“addGetRoute”方法,带有可选的第二个参数:

package http;

import http.Route;

class Router
{
    var routes: Array<Route>;

    public function new()
    {
        this.routes = [];   
    }

    public function addGetRoute(route: String, ?handler: () -> String): Void
    {
        this.routes.push(new Route(route, handler));
    }
}

这是路线class内容:

package http;

class Route
{
    var route: String;
    var handler: () -> String;

    public function new(route: String, handler: () -> String)
    {
        this.route = route;
        this.handler = handler;
    }
}

我不明白的是,编译器在看到这段代码时不会抛出错误:

this.routes.push(new Route(route, handler));

我预计它会抛出错误,因为第二个参数可以为 null。

我错过了什么吗?

默认情况下,除了基本类型 (IntFloatBool) 之外的所有内容都是 nullable in Haxe, including references to functions (and even basic types are nullable on dynamic targets). While adding ? to an argument does wrap the type in Null<T>, that doesn't have any effect if the type is already nullable. The primary reason to make an argument "optional" with ? is for it's implied = null default value,这允许在调用站点跳过它。

从 Haxe 4 开始,实际上有一个可选的 null safety 功能,它强制只有 Null<T> 可以为 null,因此会给您带来所需的编译器错误:

@:nullSafety // opt-into null safety
class Main {
    static function main() {
        new Route("example", null);
    }
}

source/Main.hx:4: characters 24-28 : Null safety: Cannot pass nullable value to not-nullable argument "handler" of function "new".

但是,请注意,零安全性仍被认为是实验性的,您可能 运行 会遇到一些粗糙的问题。