Dart实现接口方法时入参为接口实现类报类型不匹配如何解决
错误原因
Dart 对类方法重写有严格的类型安全约束:子类重写父类/接口方法时,入参类型只能与父类声明的类型一致,或是范围更宽泛的类型,不允许收窄为更具体的子类型。
你的代码里 ILogger 接口的 writeLog 约定了可以接收任意 ILog 实现类的实例,但 Logger 实现类将入参类型收窄为了具体的 Log 类,违反了上述约束,因此编译器直接抛出类型不匹配错误。
无泛型解决方案
无需引入泛型,只需要统一接口和实现类的入参类型,按需在方法内部做类型判断即可:
- 保持
ILogger接口的writeLog方法的log入参类型为ILog - 所有实现
ILogger的子类,writeLog方法的log入参也统一使用ILog类型 - 如果某个实现类需要操作具体
ILog子类的独有属性/方法,在方法内先做类型检查,Dart 会自动完成类型推断,无额外运行时开销
修正后可运行的示例代码
abstract class ILog { const ILog({required this.id}); final String id; } class Log implements ILog { const Log({required this.id}); final String id; // 示例:Log子类的独有方法 void customLogAction() {} } abstract class ILogger { void writeLog({ required ILog log, required bool persist, }); } class Logger implements ILogger { void writeLog({ required ILog log, required bool persist, }) { // 需要使用Log子类独有能力时,先做类型判断 if (log is Log) { // 此处Dart自动将log类型推断为Log,可直接调用独有方法 log.customLogAction(); } print('writing log id: ${log.id}, persist: $persist'); } } void main() { final logger = Logger(); final log = Log(id: 'abcd-1234'); logger.writeLog(log: log, persist: true); }
该方案完全兼容你将 ILog 设计为抽象类的需求,不同应用实现 ILog 子类时可以自行添加对应的序列化注解,不会侵入库的底层代码。
内容的提问来源于stack exchange,提问作者user3056783
相关产品推荐
相关产品推荐

