通过 Dart 中的子 class 参数传递超级 class 对象时没有类型错误

No type error when passing a super class object via a sub class argument in Dart

我很好奇为什么 Dart 在通过继承类型参数传入时不将 super class 标记为错误类型?将继承类型作为参数意味着应该期望使用继承类型的接口,而 super class 可能没有。这似乎是一个错误?

举例如下:

class ClassTest {
  int i;
}

void a(Object x) {
  b(x); // ClassTest inherits Object, but that doesn't mean it has the same interface
}

void b(ClassTest x){
  x.i = 2; // a() can pass a non type safe class to make this fail
}

这对我来说在编辑器中没有出现任何错误。我至少希望 'x' 在通过之前发出 as ClassTest 警告?我不确定这是否是正常行为,但我遇到过很多次。

感谢阅读。

这不是错误,而是一项功能。见 this answer from Bob Nystrom, engineer on the Dart team:

Dart is different here. It has something called "assignment compatibility" to determine which assignments are valid. Most languages just use the normal subtyping rules for this: an assignment is safe if you assign from a sub- to a supertype. Dart's assignment compatibility rules also allow assigning from a super- to a subtype.

In other words, you can downcast implicitly in an assignment, without needing any kind of explicit cast. So there's no static warning here. However, if you run the code in checked mode and that downcast turns out to be invalid (as it is here), you will get a type error at runtime when you try to assign a double to x.