Skip to content

Add "isFoo" and "asFoo" getters #22

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

Closed
carlowenig opened this issue Feb 11, 2020 · 4 comments
Closed

Add "isFoo" and "asFoo" getters #22

carlowenig opened this issue Feb 11, 2020 · 4 comments
Labels
wontfix This will not be worked on

Comments

@carlowenig
Copy link

It would be very useful, especially if Union classes are declared privately, to have getter generated which checks if the class is of a certain type. Additionally a getter to cast an object to a nested union type would be useful.

Example:

@immutable
abstract class AuthState with _$AuthState {
    const factory AuthState.authorized(User user) = _AuthStateAuthorized;
    const factory AuthState.unauthorized() = _AuthStateUnauthorized;
}

// Some logic which needs user to be authorized
if (!authState.isAuthorized) return;

final authorizedState = authState.asAuthorized; // Returns authState as _AuthStateAuthorized
@rrousselGit
Copy link
Owner

A isFoo wouldn't work with type promotion, and a asFoo would be unsafe

You should use maybeMap or maybeWhen instead

@rrousselGit rrousselGit added the wontfix This will not be worked on label Feb 11, 2020
@carlowenig
Copy link
Author

As an alternative I personally would make () => null the default/fallback value of orElse in maybeMap/maybeWhen, so the following would be easier to read and would contain less boilerplate:

Example 1:

// Current implementation
authState.maybeWhen(
  authorized: (user) {
    // Some logic for authorized users
  },
  orElse: () {},
);

// Shorter with default orElse
authState.maybeWhen(authorized: (user) {
  // Some logic for authorized users
});

Example 2:

// Current implementation
final name = authState.maybeWhen(
  authorized: (user) => user.name,
  orElse: () => null,
);

// Shorter with default orElse
final name = authState.maybeWhen(
  authorized: (user) => user.name,
);

Not that much of a change, but I think it's more concise and not an unexpected behavior since the "maybe" keyword implicates something nullable in my opinion.

@rrousselGit
Copy link
Owner

That is incompatible with non-nullable types.
It would work now, but would break soon.

@rrousselGit
Copy link
Owner

I've opened an issue on dart-lang about such orElse with NNBD:

dart-lang/language#836

For now, I would refrain on making such change, as it would cause a breaking change

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
wontfix This will not be worked on
Projects
None yet
Development

No branches or pull requests

2 participants