You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
I want to create a generic method in Dart that only accepts objects for its type T that support serialization operations, such as toJSON and fromJSON. According to the Dart specification, abstract static methods are not supported, and the reasons have been extensively discussed in this issue.
Due to this limitation, it is impossible to define a Serializable interface because there is no way to guarantee that an object has a static factory method from JSON objects. Therefore, for a case like the one described, it is not possible to enforce that constraint on the generic type.
What is the recommended workaround for these scenarios? Many solutions are proposed in the linked issue, but none seem to fit this particular case.
Thank you.
The text was updated successfully, but these errors were encountered:
Have the method accept a T Function(Object?) fromJson argument, so that anyone instantiating it with a type must also provide the factory function.
yep @lrhn , that's one the workarounds I thought about. However, it's not very safe option IMHO: the user of the API would be in charge of passing the appropriate object parser each time, which could lead to errors
With the language as it is today, I think Lasse's suggestion is about the best you can do. If a bare callback function feels a little too raw for your, the other common pattern is to pass in a factory object that knows how to create objects of various types from the corresponding JSON. So the factory would be responsible for handling the fromJson() side of things.
I'm going to go ahead and close this issue because it's not actionable as a language change, but I agree this is definitely a sore spot in the language. For serialization in particular, our hope is that macros will solve a lot of problems. As I commented in #356, I would also really love to do metaclasses, but that's a much more nebulous idea that would be a longer ways out.
I want to create a generic method in Dart that only accepts objects for its type T that support serialization operations, such as toJSON and fromJSON. According to the Dart specification, abstract static methods are not supported, and the reasons have been extensively discussed in this issue.
Due to this limitation, it is impossible to define a Serializable interface because there is no way to guarantee that an object has a static factory method from JSON objects. Therefore, for a case like the one described, it is not possible to enforce that constraint on the generic type.
What is the recommended workaround for these scenarios? Many solutions are proposed in the linked issue, but none seem to fit this particular case.
Thank you.
The text was updated successfully, but these errors were encountered: