Why List() constructor is not accessible in Dart's null safety?

匆匆过客 提交于 2021-01-28 03:51:30

问题


With NNBD, you're not allowed to initialise the list using the default constructor:

List<int> foo = List(); // Compile time error

However, you can still do:

List<int> foo = []; // No error

So, what's the difference between the two? Either both of them should show the error or none of them.


回答1:


The List constructor had two uses:

  • new List() to create an empty growable list, equivalent to [].
  • new List(n) to create a fixed-length list of length n filled with null values

With null safety, the second use was unsound most of the time, and there was no good way to fix it. It's possible to force a type argument to be non-nullable, but List<T>(4) only works when T is nullable. There is no way to enforce that.

So, the List(n) mode needed to go (replaced by List.filled(n, value) which forces you to provide a fill-value). That left List(), which doesn't really carry its own weight. You can just use [] instead (and you should!), so it was decided to remove the constructor entirely - all uses of it was either unsafe or useless. (Also, it was a weird constructor already, because if we wanted to properly make it null safe, it would have an optional parameter with a non-nullable type and no default value.)

By removing it completely, it makes it possible to, potentially, introduce a new List constructor in the future, perhaps as a shorter alias for List.filled. One can hope.



来源:https://stackoverflow.com/questions/63451506/why-list-constructor-is-not-accessible-in-darts-null-safety

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!