Skip to content

feat: Add abstract copyWith method to sealed classes - #4238

Merged
marcelomendoncasoares merged 9 commits into
mainfrom
copilot/add-fromjson-copywith-methods
Nov 18, 2025
Merged

marcelomendoncasoares merged 9 commits into
mainfrom
copilot/add-fromjson-copywith-methods

Conversation

Copilot AI commented Nov 17, 2025 •

Copy link
Copy Markdown
Contributor

Sealed classes in Serverpod now support polymorphic copyWith operations. Previously, copyWith could only be called on concrete child types, limiting generic code that operates on sealed hierarchies.

Note: While the original issue (#3173) requested both fromJson and copyWith abstract methods, only copyWith was implemented as abstract. The fromJson method is always implemented as a factory constructor and doesn't benefit from being abstract on the parent class.

Pre-launch Checklist

  • I read the Contribute page and followed the process outlined there for submitting PRs.
  • This update contains only one single feature or bug fix and nothing else.
  • I read and followed the Dart Style Guide and formatted the code with dart format.
  • I listed at least one issue that this PR fixes in the description above.
  • I updated/added relevant documentation (doc comments with ///), and made sure that the documentation follows the same style as other Serverpod documentation. I checked spelling and grammar.
  • I added new tests to check the change I am making.
  • All existing and new tests are passing.
  • Any breaking changes are documented below.

Breaking changes

None. This is additive - existing code continues to work unchanged. Child classes gain the @override annotation on their existing copyWith methods.

Changes Made

Code generation updates:

  • Sealed parent classes now declare abstract copyWith method
  • Child classes implement copyWith with @override annotation
  • Enables polymorphic copying without knowing concrete types
  • Added test assertions to verify abstract methods are properly generated (EmptyFunctionBody)
  • Added comprehensive tests for sealed classes used as field types in other models

Example usage:

// Polymorphic copyWith
SealedParent parent = getChild();
parent.copyWith(...);  // ✅ Dispatches to concrete implementation

// Sealed classes as field types
class ObjectWithSealedClass {
  SealedParent sealedField;
  SealedParent? nullableSealedField;
  List<SealedParent> sealedList;
  // ... works correctly with serialization/deserialization
}

Generated code:

sealed class SealedParent {
  /// Returns a shallow copy of this [SealedParent]
  /// with some or all fields replaced by the given arguments.
  @useResult
  SealedParent copyWith({...});
}

class SealedChild extends SealedParent {
  factory SealedChild.fromJson(...) {...}
  
  @override
  SealedChild copyWith({...}) {...}
}

Testing

Unit Tests:

  • 54 sealed class tests (including abstract method verification and field type tests)
  • 709 server code generator tests
  • All tests passing

Integration Tests:

  • Created ObjectWithSealedClass model demonstrating sealed class fields (sealedField, nullableSealedField, sealedList)
  • Tests in both server and client verify:
    • Object creation with sealed class fields
    • Serialization preserves type information (__className)
    • Deserialization reconstructs correct child types
    • Type safety maintained throughout
  • 19 inheritance polymorphism tests in each test suite

This implementation enables generic code to work with sealed class hierarchies without knowing the concrete types, using copyWith polymorphically and supporting sealed classes as field types in other models with full serialization/deserialization support.

Original prompt

This section details on the original issue you should resolve

<issue_title>Add fromJson and copyWith abstract methods to sealed classes for child interoperability</issue_title>
<issue_description>### 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</issue_description>

Comments on the Issue (you are @copilot in this section)


💬 We'd love your input! Share your thoughts on Copilot coding agent in our 2 minute survey.

@coderabbitai

This comment was marked as resolved.

Copilot AI and others added 3 commits November 17, 2025 14:39
- Added abstract `fromJson` method to sealed parent classes
- Added abstract `copyWith` method to sealed parent classes
- Child classes now implement these methods with @OverRide
- Instance `fromJson` method added to children of sealed parents
- Updated override logic to handle sealed parent classes correctly

Co-authored-by: marcelomendoncasoares <[email protected]>
- Updated _buildCopyWithMethod to add @OverRide when parent is sealed
- Made classDefinition parameter optional (null for impl classes)
- Updated all sealed class tests to expect new behavior
- Added tests for abstract fromJson method on sealed parents
- Added tests for instance fromJson with @OverRide on children
- All 55 sealed class tests now passing

Co-authored-by: marcelomendoncasoares <[email protected]>
- Created test demonstrating polymorphic copyWith and fromJson usage
- Verified sealed classes can be used polymorphically via parent type
- Both tests pass successfully

Co-authored-by: marcelomendoncasoares <[email protected]>
Copilot AI changed the title [WIP] Add fromJson and copyWith methods to sealed classes feat: Add abstract fromJson and copyWith methods to sealed classes Nov 17, 2025

@marcelomendoncasoares marcelomendoncasoares left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@copilot Please address my comments. Make sure to run dart format before committing to avoid CI errors.

- Removed abstract fromJson method from sealed parent classes
- Removed instance fromJson method from child classes
- Kept abstract copyWith method on sealed parents
- Removed comments from code
- Moved copyWith test to inheritance_polymorphism_test.dart
- Removed sealed_polymorphism_test.dart file
- Updated sealed_class_test.dart to remove fromJson tests
- Ran dart format on all modified files
- All tests passing (705 tests)

Co-authored-by: marcelomendoncasoares <[email protected]>

Copilot AI commented Nov 18, 2025 •

Copy link
Copy Markdown
Contributor Author

@copilot Please address my comments. Make sure to run dart format before committing to avoid CI errors.

Addressed all review comments. Removed abstract fromJson method (kept only copyWith), removed comments, moved tests, and ran dart format on all modified files. All 705 tests passing. (commit 0a58908)

Warning

Firewall rules blocked me from connecting to one or more addresses (expand for details)

I tried to connect to the following addresses, but was blocked by firewall rules:

  • api.mixpanel.com
    • Triggering command: dart run serverpod_cli generate (dns block)

If you need me to access, download, or install something from one of these locations, you can either:

Copilot AI changed the title feat: Add abstract fromJson and copyWith methods to sealed classes feat: Add abstract copyWith method to sealed classes Nov 18, 2025

@marcelomendoncasoares marcelomendoncasoares left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@copilot Please address my final comments.

- Added expect assertions to verify copyWith is abstract (EmptyFunctionBody)
- Removed comment from _shouldOverrideAbstractCopyWithMethod
- All 50 sealed class tests passing with proper abstract checks

Co-authored-by: marcelomendoncasoares <[email protected]>

Copilot AI commented Nov 18, 2025

Copy link
Copy Markdown
Contributor Author

Just as a heads up, I was blocked by some firewall rules while working on your feedback. Expand below for details.

Warning

Firewall rules blocked me from connecting to one or more addresses (expand for details)

I tried to connect to the following addresses, but was blocked by firewall rules:

  • api.mixpanel.com
    • Triggering command: dart run serverpod_cli generate (dns block)

If you need me to access, download, or install something from one of these locations, you can either:

@marcelomendoncasoares marcelomendoncasoares left a comment •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@copilot Add one final unit test on tools/serverpod_cli/test/generator/dart/server_code_generator/sealed_class_test.dart with this case to ensure that sealed classes can be used as types on fields of other models. The model must compile correctly. Then, add one final integration test on the serverpod_test_server with the same purpose. For such, create a new model on the project that contains a sealed class and assert that it is being correctly generated.

- Added unit test in sealed_class_test.dart verifying sealed classes can be used as field types
- Created ObjectWithSealedClass model with sealed class fields
- Added integration tests in both server and client test files
- Tests verify serialization, deserialization, and type safety
- All 709 code generator tests passing
- All 19 inheritance polymorphism tests passing

Co-authored-by: marcelomendoncasoares <[email protected]>

Copilot AI commented Nov 18, 2025 •

Copy link
Copy Markdown
Contributor Author

@copilot Add one final unit test on tools/serverpod_cli/test/generator/dart/server_code_generator/sealed_class_test.dart with this case to ensure that sealed classes can be used as types on fields o...

Added comprehensive tests for sealed classes as field types:

Unit Test (sealed_class_test.dart):

  • Created test case verifying sealed classes can be used as field types in other models
  • Tests both nullable and non-nullable sealed class fields
  • Verifies generated code compiles without errors

Integration Tests (inheritance_polymorphism_test.dart):

  • Created ObjectWithSealedClass model with sealed class fields (sealedField, nullableSealedField, sealedList)
  • Added tests in both server and client test files
  • Tests verify:
    • Object creation with sealed class fields
    • Serialization preserves type information (__className)
    • Deserialization reconstructs correct child types
    • Type safety maintained (can cast to specific child types)

All tests passing (54 unit tests, 19 integration tests). (commit 1e3dfc8)

Warning

Firewall rules blocked me from connecting to one or more addresses (expand for details)

I tried to connect to the following addresses, but was blocked by firewall rules:

  • api.mixpanel.com
    • Triggering command: dart run serverpod_cli generate (dns block)

If you need me to access, download, or install something from one of these locations, you can either:

@marcelomendoncasoares
marcelomendoncasoares marked this pull request as ready for review November 18, 2025 03:12
@marcelomendoncasoares
marcelomendoncasoares requested a review from a team November 18, 2025 03:12

@SandPod SandPod left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM! 👍

@marcelomendoncasoares
marcelomendoncasoares merged commit 955b8cd into main Nov 18, 2025
@marcelomendoncasoares
marcelomendoncasoares deleted the copilot/add-fromjson-copywith-methods branch November 18, 2025 11:36
@github-actions github-actions Bot locked and limited conversation to collaborators Nov 18, 2025
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

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

3 participants