I want to add my own methods to a few Dart Classes

烂漫一生 提交于 2019-12-08 02:06:12

问题


My attempt to simply 'Extend' the Map class fails because List is an interface and cannot be extended but must be implemented.

The goal was simply to add a few methods on top of some existing class such as:

List.add_unique(item) where I only want to append if the item does not already exist. This can be done nicely by and-ing the append !=null logic with List.indexOf(item) != -1 (where -1 is notFound). This would be a good and easy to understand example?

But, how to accomplish this in the shortest, least overall overhead sort of way? I think I would be OK with loose typing - at least to start with.

There are other methods I wish to add and or modify such as an .add() method for the Map class.

I have not dealt with interfaces for many years and I'm thinking there might just be a much easier way overall to get started on this side of my project.

Thanks!


回答1:


I've hit this problem too. The best workaround at the moment is to create a class that forwards all of the method calls. Something like: https://github.com/dart-lang/html5lib/blob/master/lib/src/list_proxy.dart

Then you can inherit from ListProxy and override or add whatever methods you need.

If people find this useful enough, maybe we can put it in its own pub package. I'm hoping we can get dart:core fixed, though, so it supports inheritance from all of the core collection classes.

By the way, if you're trying to override a method in Map it's much easier: you can import 'dart:coreimpl'; and extend HashMapImplementation.



来源:https://stackoverflow.com/questions/12925019/i-want-to-add-my-own-methods-to-a-few-dart-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!