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

Support sealed classes #29

Closed
BWhiteApps opened this issue Apr 25, 2024 · 1 comment
Closed

Support sealed classes #29

BWhiteApps opened this issue Apr 25, 2024 · 1 comment
Labels
enhancement New feature or request

Comments

@BWhiteApps
Copy link

One change that would make genq an excellent freezed replacement would be to support unions with sealed classes.
Example

@genq
sealed class HomeState with _$HomeState {
  const factory HomeState.loading() = LoadingState;
  const factory HomeState.loaded(String data) = LoadedState;
  const factory HomeState.error(String message) = ErrorState;
}

It would be great if this was able to generate a sealed classes that could be used with dart's pattern matching. Here is more details on how this would be useful:
https://medium.com/@aliammariraq/sealed-classes-in-dart-unlocking-powerful-features-d8dba185925f

@jankuss
Copy link
Owner

jankuss commented Apr 26, 2024

If you require sealed classes, genq already supports the following:

import 'package:genq/genq.dart';

part 'input.genq.dart';

sealed class State {}

@genq
class LoadingState extends State with _$LoadingState {
  const factory LoadingState() = _LoadingState;
}

@genq
class SuccessState extends State with _$SuccessState {
  const factory SuccessState({
    required String name,
    required int age,
  }) = _SuccessState;
}

void main() {
  final State state = LoadingState();

  final result = switch(state) {
    LoadingState() => 'Loading',
    SuccessState(name: 'John', age: 30) => 'A 30 year old John',
    SuccessState(name: final name, age: 1) => '$name is just 1 year old',
    SuccessState(name: final name, age: final age) => '$name is $age years old',
  };

  print(result);
}

It definetly is not as pretty as the requested syntax, but works if you need sealed classes.
Regarding the requested syntax, #30 tracks this feature request. So I will close this for now.

@jankuss jankuss closed this as completed Apr 26, 2024
@jankuss jankuss added question Further information is requested enhancement New feature or request and removed question Further information is requested labels Apr 26, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants