gpt4 book ai didi

flutter - Dart + flutter : why doesn't the compiler recognize type mismatches

转载 作者:IT王子 更新时间:2023-10-29 06:50:31 26 4
gpt4 key购买 nike

我将我的 flutter 应用程序的数据封装在一个名为 AppData 的类中。它看起来有点像这样:

class AppData with ChangeNotifier{
List<word.Word> _words;
UnmodifiableListView<word.Word> words;

AppData(){
// at some point this will be loaded from disk
// for now I'm just using a hardcoded list of words
_words = word.words;

// the following code would work:
// words = UnmodifiableListView(_words);

// this doesn't, but it's also not a compiler error !?
words = _words;
}

// ...
}

AppData 类跟踪单词列表。对于 AppData 的消费者,这是可见的 UnModifiableListView

我的代码有一个非常明显的错误:我将 _words 分配给 words 而没有将 List 封装在 UnModifiableListView 正确。为什么编译器找不到它?

类型应该明显不匹配。来自dart docs (强调我的):

Dart’s type system, like the type systems in Java and C#, is sound. It enforces that soundness using a combination of static checking (compile-time errors) and runtime checks. For example, assigning a String to int is a compile-time error. Casting an Object to a string using as String fails with a runtime error if the object isn’t a string.

更新,回应雷米的回答:

错误信息是:

The following assertion was thrown building MultiProvider:
type 'List<Word>' is not a subtype of type 'UnmodifiableListView<Word>'

这似乎是协变与逆变的问题。

如果我知道我对 List 的引用实际上包含一个 UnmodifiableListView,那么我就可以自己进行转换。为什么编译器会为我添加隐式转换?

在我看来,这似乎绕过了上面文档中提到的许多类型可靠性。特别是当我更改我的类型层次结构并进行大量重构时,我依赖编译器告诉我:你把类型搞混了。他们的继承树很可能在某个时候仍然到达一个共同的祖先。但它们绝对不一样。

至少对我来说,这更令人惊讶,因为这不是其他“典型”OOP 语言(Java、C#、...)的工作方式。

所以我还是很疑惑:为什么编译器找不到这个,这个设计背后的原因是什么?

最佳答案

实际上,发生的是隐式转换。

由于 UnmodifiableListView 是一个 List,将 List 分配给 UnmodifiableListView 会自动转换。

您可以像这样在 analysis_options.yaml 上禁用它:

analyzer:
strong-mode:
implicit-casts: false

关于flutter - Dart + flutter : why doesn't the compiler recognize type mismatches,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56777311/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com