Dart方法重写规则咨询:参数类型不匹配报错解析
Dart方法重写的参数类型规则及报错解决
你的代码
void main() { Child c = new Child(); c.m1("12"); } class Parent { void m1(int a) { print("value of a $a"); } } class Child extends Parent { @override void m1(String b) { print("value of b $b"); } }
报错信息
Error: The parameter 'b' of the method 'Child.m1' has type 'String', which does not match the corresponding type, 'int', in the overridden method, 'Parent.m1'. Change to a supertype of 'int', or, for a covariant parameter, a subtype.
Dart方法重写的参数类型要求
Dart为保证类型安全,对方法重写的参数类型有明确限制:
- 默认遵循逆变规则:子类重写父类方法时,参数类型必须是父类对应参数类型的超类型。比如父类参数是
int,子类参数可以是Object(所有类型都是Object的子类),但不能是String——因为String和int无继承关系,既不是int的超类型,也不是其子类型。 - 若需用父类参数的子类型重写,可在父类参数前加
covariant关键字,但需自行保证类型安全(比如避免用父类引用指向子类实例时传入不兼容类型)。
针对你的代码的解决方案
方案1:遵循逆变规则修改参数类型
将子类m1的参数类型改为int的超类型(如Object),既符合重写规则,也能处理字符串输入:
void main() { Child c = new Child(); c.m1("12"); } class Parent { void m1(int a) { print("value of a $a"); } } class Child extends Parent { @override void m1(Object b) { print("value of b $b"); } }
方案2:使用covariant关键字(注意风险)
若业务逻辑确实需要子类用String作为参数,可给父类参数添加covariant,但要注意:用父类引用指向子类实例时,传入父类定义的int类型会触发运行时错误,因为子类实际接收的是String。
void main() { Child c = new Child(); c.m1("12"); // 正常运行 // 以下代码会报错,需避免 // Parent p = Child(); // p.m1(12); // 运行时类型不匹配 } class Parent { void m1(covariant int a) { print("value of a $a"); } } class Child extends Parent { @override void m1(String b) { print("value of b $b"); } }
额外说明
Dart不支持方法重载(同一类中不能有同名但参数不同的方法),因此无法在子类中同时保留父类的m1(int)和自己的m1(String),只能通过重写规则调整,或改用不同方法名。
内容的提问来源于stack exchange,提问作者AlexPy
相关产品推荐
相关产品推荐

