Skip to content

Allow case condition in return statement #4092

Closed as not planned
Closed as not planned
@alex-medinsh

Description

@alex-medinsh

Trying to refactor a simple function that validates a Uri:

bool _validateUri(Uri uri) {
      return uri.path == '/path' &&
          uri.queryParameters['param1'] == 'param1' &&
          uri.queryParameters['param2'] == 'param2' &&
          uri.queryParameters['param3'] != null &&
          uri.queryParameters['param4'] != null;
}

I have followed my instincts and wrote this code using patters:

bool _validateUri(Uri uri) {
     return uri.path == '/path' && uri.queryParameters case {
         'param1': 'param1',
         'param2': 'param2',
         'param3': String _,
         'param4': String _,
     };
}

and found out that I can't use case conditions anywhere outside an if. Furthermore, when I changed the code to use an if condition I found out that I can only use a single case condition in the if.

I got this to work with a switch and a single pattern:

bool _validateUrl(Uri uri) {
    return switch (uri) {
      Uri(
        path: '/path',
        queryParameters: {
         'param1': 'param1',
          'param2': 'param2',
          'param3': String _,
          'param4': String _,
        },
      ) => true,
      _ => false,
   };
}

But this approach requires me to explicitly return true and have a default false case, when all I want is to just return a bool result of "this variable did(n't) match this pattern".

In my opinion it would be useful and intuitive to be able to use case conditions outside of if and to chain multiple conditions with case. This might be two separate issues, but this was my thought process when trying to refactor this function.

Metadata

Metadata

Assignees

No one assigned

    Labels

    requestRequests to resolve a particular developer problem

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions