Skip to content

Add fromJson and copyWith abstract methods to sealed classes for child interoperability #4237

Closed

Description

@marcelomendoncasoares

Problem to Solve

Currently, when using sealed classes in Serverpod, there is no way to generically call fromJson or copyWith on the abstract parent class and have it dispatch correctly to the child classes. This is problematic in code that wants to operate on lists or collections of sealed base types and expects to be able to construct or clone objects without knowing their concrete type. This pattern is very common (and useful) with sealed/unions, and its absence reduces code flexibility when handling Serverpod models in a generic way.

Proposal

Introduce abstract methods for fromJson and copyWith on sealed classes in the generated code, requiring that all child classes implement these methods. The code generator can ensure that each sealed child class provides a concrete implementation, enabling applications and libraries to use these constructors and copy utilities using only the abstract type. This could look like:

abstract class MyBase {
  MyBase fromJson(Map<String, dynamic> json);
  MyBase copyWith(...);
}

class A extends MyBase { ... }
class B extends MyBase { ... }

This approach means code working with MyBase does not need to know about all concrete types in advance. This is particularly helpful for plugins, dynamic model deserialization, and generic libraries.

Use Case

Work with child classes of sealed models on endpoints, since PR #4227 implemented support for polymorphism.

Alternatives

No alternative allow using sealed classes this way.

Additional context

This issue was highlighted on #3173 (comment).

How experienced are you with this library?

Expert - Experienced and comfortable with using this library in complex projects

Are you interested in working on a PR for this?

  • I want to work on this
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area: modelsenhancement

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions