Otskimanot Sqilal
Otskimanot Sqilal

Reputation: 2402

dart extends from Map generate an error that the default constructor in Map is not generative

I'm trying to extends from Map like this :

class TestClass extends Map {
}

Just by doing that i got an error Constructor '<default>' in class 'Map<dynamic, dynamic>' is not generative.

Don't know what to do, i add this : TestClass() : super();

I still got that same error.

Extra question :

Which one is the best approach, by extending Map like above or make a new class that has a property of a Map like this :

class TestClass {
    Map attr;
}

Upvotes: 1

Views: 1133

Answers (2)

Nashev
Nashev

Reputation: 635

You can use a type aliasing (https://medium.com/dartlang/announcing-dart-2-13-c6d547b57067) instead of extending a Map.

Just write typedef TestClass = Map<String, YourClass>;

Upvotes: 1

Mason Bryant
Mason Bryant

Reputation: 1392

Map is an abstract class (see: http://api.dartlang.org/docs/releases/latest/dart_core/Map.html) with a factory that (looking at the source code) creates a default HashMap implementation.

(you can see most of this yourself from the editor: rightclick "map" and select "open Declaration")

Simply calling the factory results in an error about HashMap not being a subclass of your class.

But I think that simply subclassing HashMap will give you what you want since that is the default implementation anyway.

To your extra question: subclassing a hashmap is often an anti-pattern (at least in Java, please correct me if something about Dart makes it safer) and rarely what you want to do, especially if containment will work. I'd recommend that.

Upvotes: 1

Related Questions