[go: nahoru, domu]

Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Generic method constrained to objects supporting serialization #3881

Open
pitazzo opened this issue Jun 5, 2024 · 2 comments
Open

Generic method constrained to objects supporting serialization #3881

pitazzo opened this issue Jun 5, 2024 · 2 comments
Labels
request Requests to resolve a particular developer problem

Comments

@pitazzo
Copy link
pitazzo commented Jun 5, 2024

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.

@pitazzo pitazzo added the request Requests to resolve a particular developer problem label Jun 5, 2024
@lrhn
Copy link
Member
lrhn commented Jun 5, 2024

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
Copy link
Author
pitazzo commented Jun 5, 2024

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
request Requests to resolve a particular developer problem
Projects
None yet
Development

No branches or pull requests

2 participants