Skip to content

Make patterns more lenient when destructuring objects into new local variables. #3189

@rrousselGit

Description

@rrousselGit

Hello!

Background

Consider the following code:

void main() {
  final [first] = [1, 2, 3];

  print(first);
}

Surprisingly, it throws Bad state: Pattern matching error.

This feels very unexpected to me. I would expect destructuring to be able to pick only one value of a pattern.
That is how destructuring works on other languages such as JS:

const [first] = [1, 2, 3]
console.log(1) // correctly prints 1

I get that the expected syntax is to instead write:

final [first, ...] = [1, 2, 3];

but this feels quite unnatural and error-prone to me. The fact that we get a runtime exception here bothers me quite a bit personally.
I would've never expected an exception to be thrown before running the code.

The same issue appears to happen with records:

var (positional, ) = (1, 2, 3);
var (:named) = (named: 42, another: 21);

Here, we get a compilation error. We're instead expected to write:

var (positional, _, _) = (1, 2, 3);
var (:named, another: _) = (named: 42, another: 21);

For similar reasons, that too feels unexpected to me.

Proposal

Could we make patterns less strict when doing destructuring against new local variables?
Such as implying a ... when doing a list destructuring, or filling in the missing properties when doing a record destructuring.

The fact that we can get possible runtime/compile errors here seems surprising to me. It makes destructuring a bit brittle and not intuitive for folks using destructuring in languages.

To me, there should be no pattern matching involved in the destructuring of objects into variable declarations.
To begin with, we cannot write:

var (name, 42) = ('John', 42)

So the fact that we need to write var (name, _) = seems inconsistent to me.

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