Type error when passing superclass object via subclass argument in Dart

I'm wondering why Dart doesn't indicate the superclass as the wrong type when passed through an inherited type argument? Taking an inherited type as a parameter means that the interface of the inherited type must expect to be used, which a superclass cannot have. Does this look like a bug?

See example below:

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
}

      

This does not throw errors in the editor for me. At least I was expecting a warning before "x" is sent as ClassTest

before sending it? I'm not sure if this is normal behavior, but I came across quite a bit of it.

Thanks for reading.

+3


source to share


1 answer


This is not a bug, this is a feature. See this answer from Bob Nystrom, Dart's team engineer :



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: assignment is safe as long as you assign from a subtype to a supertype. The Dart assignment compatibility rules also allow assignment from a super subtype.

In other words, you can hide implicitly in the job without any explicit actuation. Therefore, there is no static warning here. However, if you run the code in check mode and that the downcast is invalid (as it is here), you will get a runtime type error when you try to assign double x.

+3


source







All Articles