dart-lang / language

Design of the Dart language
Other
2.62k stars 198 forks source link

Generic method constrained to objects supporting serialization #3881

Open pitazzo opened 1 month ago

pitazzo commented 1 month ago

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.

lrhn commented 1 month ago

Have the method accept a T Function(Object?) fromJson argument, so that anyone instantiating it with a type must also provide the factory function.

pitazzo commented 1 month ago

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