Search code examples
dartdart-null-safety

Why Dart Null Safety principles only apply on the statically typed variables not type inferred?


I am studying dart null safety concepts and I have found that all principles apply only on the statically typed variables, int a for example, not on the type inferred the ones declare with 'var' keyword. Why do null safety rules apply to one of the variables created with the 'var' keyword? I just want to the reason why dart doesn't deal with type inferred variables. Thank you


Solution

  • I am studying dart null safety concepts and I have found that all principles apply only on the statically typed variables, int a for example, not on the type inferred the ones declare with var keyword.

    Null-safety concepts do apply to inferred types:

    int? f() => 42;
    
    var x = f(); // The static type of `x` is `int?`.
    

    It's true that you currently can't write var? to explicitly declare that a variable should use a nullable version of the inferred type. It's something that the Dart language team has considered and is still open to adding. See:

    where Lasse Nielsen explains:

    The reason var? is not supported is, roughly, that ? is something you add on types, and var is not a type. It's a declaration marker that occurs instead of a type, like final - except that final can also be combined with at type, while var can't.

    The cases where you'd want to use var? are if you have a non-null initial value and want to set that variable to null later. In practice, I'd expect those situations aren't very common, so it's not a prioritized feature. For such cases, you should declare the variable with an explicit type (e.g. int? x = 42;).

    If you really want to avoid typing the typename, you could apply Erik Ernst's suggestion. For example: var x = null ?? 42;.

    Alternatively you could make a helper function:

    T? makeNullable<T>(T object) => object;
    
    var x = makeNullable(42);
    

    But I personally think those approaches are overkill and are less readable.