Pieter-Jan de Vries
Pieter-Jan de Vries

Reputation: 81

How to properly override operator [] of MapBase

I created a simple class, extending MapBase<String, String>. All looks well, except the operator [] override. This is the code:

class MyMap extends MapBase<String, String> {

  Map<String, String> _map = {};

  @override
  Iterable<String> get keys => _map.keys;

  @override
  String remove(Object key) => _map.remove(key);

  @override
  void clear() => _map.clear();

  @override
  operator []= (String key, String value) => _map[key] = value;

  @override
  String operator [] (String key) => _map[key];
}

The @override operator [] results in the following error:

error: 'MyMap.[]' ('(String) → String') isn't a valid override of 'Map.[]' ('(Object) → String'). (invalid_override at [joap] lib\api\api_query.dart:43)ˋ
error: 'MyMap.[]' ('(String) → String') isn't a valid override of 'MapMixin.[]' ('(Object) → String'). (invalid_override at [joap] lib\api\api_query.dart:43)

I find this strange, because the @override operator []= does not show this error. Removing the String type from the key parameter resolves the problem.

What am I doing wrong here?

Upvotes: 1

Views: 433

Answers (1)

jamesdlin
jamesdlin

Reputation: 90105

The signature for your operator[] override doesn't match the base signature.

Map's operator[] takes an Object argument, not the type of the Key. (In contrast, operator[]= does take the Key type as its argument.)

(I found this surprising, but there is rationale for it.)

Upvotes: 1

Related Questions