【问题标题】:Incorrectly assigning a variable of custom type does not give an error in static type check错误地分配自定义类型的变量不会在静态类型检查中出错
【发布时间】:2021-05-13 00:51:32
【问题描述】:

我正在分配Function(String) 类型的变量stringFn,例如:

Function(String) stringFn = (String? s) {};

即使为stringFn 分配了一个可以接收可为空参数的函数,dart 静态类型检查也不会出错。

打印 stringFn 的 runtimeType 会导致 (String?) => Null 但如果我调用该函数:

stringFn(null);

导致The argument type 'Null' can't be assigned to the parameter type 'String' 我同意,因为该类型不允许可空参数。

我在这里错过了什么吗?

【问题讨论】:

    标签: flutter dart dart-null-safety


    【解决方案1】:

    这是预期的行为。 String? 可以被认为是比String 的泛型类型,因为它可以接受所有Strings null

    因此,传递给Function(String) 的任何String 都可以保证由您的(String? s){} 正确处理。 stringFn 声称它可以根据其变量类型处理所有非空 String 值。 (String? s){} 知道如何处理所有非空的Strings 除了null,所以代码是有效的。

    您会看到,如果您尝试将null 传递给stringFn,您应该得到一个静态分析错误,而不是运行时:

    void main() {
      Function(String) stringFn = (String? s) {};
      
      stringFn(null);//The argument type 'Null' can't be assigned to the parameter type 'String'
    }
    

    尝试反向操作(翻转类型和赋值)将在stringFn 行显示静态分析错误:

    void main() {
      Function(String?) stringFn = (String s) {};//The argument type 'Null Function(String)' can't be assigned to the parameter type 'dynamic Function(String?)'
      
      stringFn(null);
    }
    

    这再次是预期的,因为您的参数(String s){} 不知道如何处理可为空的类型,因为您的变量类型暗示它应该这样做。根据stringFn的类型,null应该处理得当,而(String s){}就不行了。

    【讨论】:

    • 我想我明白了。所以在这种情况下,Function(String) stringFn = (String? s){}Function(String) stringFn = (String s){} 在函数调用过程中不会有区别,因为前者更通用的赋值受类型的限制。
    • @CalvinGonsalves 是的,它们都是等价的。
    猜你喜欢
    • 2020-10-02
    • 2014-07-10
    • 2021-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-29
    • 2022-10-13
    相关资源
    最近更新 更多