jasxir
jasxir

Reputation: 918

Dart: Is is possible to make a factory method polymorphic?

Yes it's related to JSON deserialization. I have a class JsonStringSerializable

abstract class JsonStringSerializable {
  Map<String, dynamic> toJson();
}

Which I can extend

class Cat extends JsonStringSerializable {

  @override
  Map<String, dynamic> toJson() => null;

  factory Cat.fromJson(Map<String, dynamic> json) => null;
}

So now I can use any instance of JsonStringSerializable and expect the implementation of toJson.

My question is how can I do the same with fromJson? Is it possible in Dart?

Upvotes: 1

Views: 1033

Answers (1)

lrn
lrn

Reputation: 71623

No.

A factory constructor, generative constructor or static method is not part of any interface. That means that you cannot abstract over them using a type. There is no type for "something which has a toJson(Map<String,dynamic>) constructor or static method".

The one thing you can do is to abstract over the function itself.

T createFromJson<T>(T fromJson(Map<String, dynamic> json), Map<String, dynamic> json) =>
  fromJson(json);

Then you can call that function with a function calling the constructor (or if you used a static method instead, directly with the tear-off of that method):

  createFromJson((map) => Cat.fromJson(map), json);

Upvotes: 6

Related Questions