Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

dart - void Function(int) isn't a valid override of void Function(dynamic)

class Parent<T> {
  void method(T t) {}
}

class Child extends Parent {
  @override
  void method(int i) {} // error: mentioned_below

  void takesDynamic(dynamic d) {
    takesType(d); // no error
  }

  void takesType(int i) {
    takesDynamic(i); // no error
  }
}

Error:

void Function(int) isn't a valid override of void Function(dynamic)

When I can easily pass int to dynamic and vice-versa in a method parameter, why do I see the error when I override method.


PS:

I am not looking for a solution which is to use extends Parent<int> and get it working, I want to know the reason why things are treated differently when I am overriding a method vs calling regular methods.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

void Function(int x) normally isn't a valid override of void Function(dynamic x) because the int version is not substitutable for the dynamic version.

What are the allowed inputs to Parent<dynamic>.method? Anything.

What are the allowed inputs to Child.method? Just ints.

Such an override therefore could violate the contract of Parent<dynamic>'s interface. (For example, what if you had an instance of Child and passed it to something that expected Parent<dynamic>, which then invoked method('not an int') on it?)

(Note that this is not specific to method overrides. In general, a function that takes a narrower type cannot be used where a function that takes a wider type is expected, even if the narrower type derives from the wider type.)

Dart does allow you to use the covariant keyword to suppress the static type error and explicitly allow the override, but be aware that doing so isn't necessarily type-safe, and you would be responsible for ensuring that you don't get type errors at runtime.

Further reading: Covariance and contravariance (computer science) from Wikipedia


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...