【问题标题】:Why is the type checking in Dart such strange?为什么 Dart 中的类型检查如此奇怪?
【发布时间】:2020-12-20 21:06:33
【问题描述】:

给定代码

List<int> rawList = [0, 1, 2];
BuiltList<int> list = rawList.map((n) => n * 2);

编译成功,但在运行时失败并出现错误

type 'MappedListIterable' 不是 type 的子类型 '内置列表'

那么为什么它不会在编译阶段崩溃呢?请解释一下,在 C# 和 Kotlin 之后我无法理解。

【问题讨论】:

  • 该代码实际上给了我编译时错误(至少 IDE 显示它是错误的)
  • BuildList的声明是什么?
  • @BambinoUA 它来自built_collection pub.dev/packages/built_collection

标签: flutter generics dart typechecking compile-time-type-checking


【解决方案1】:

.map 返回一个Iterable&lt;int&gt;,它不适合您的List&lt;int&gt;。您需要使用.toList()Iterable 转换为List

【讨论】:

  • 是的,List 是一个 Iterable,所以 List 可以在任何你想要 Iterable 的地方使用。但是你有另一个方向:你希望 Iterable 表现得像一个 List。不去。因此需要额外的 .toList()。
  • @BambinoUA 我猜它并没有违反 Liskov 替换原则
  • @RandalSchwartz 谢谢,但我理解错误的原因。我的问题是为什么它是运行时错误而不是编译时间。
  • 不知道。也许 NNBD 中有一些东西可以更好地执行它。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-07-21
  • 2021-11-01
  • 1970-01-01
  • 2017-03-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多