Skip to content

Named arguments #4185

Open
Open
@cedvdb

Description

@cedvdb

Named argument

As opposed to named parameters, named arguments is about using the parameter name on the call site.

Named arguments enable you to specify an argument for a positional parameter by matching the argument with its name rather than with its position in the parameter list.

Example:

void main() {
  final a = A(x: 1, y: 2);
  final another = A(y: 2, x:1);
}

class A {
  final int x;
  final int y;
  A(this.x, this.y);
}

Rationale:

The decision to use named or positional arguments can be a decision the call site should make.

Private properties

void main() {
  final a = A(x: 1, y: 2);
}

class A {
  final int _x;
  final int _y;
  A(this._x, this._y);
}

This could lead to other beneficial features down the line like:

Declaring all fields in a constructor

class A {
  final int x;
  final int y;
  final int z;
  A(this.*);
}

Related: Object spread shorthand

Syntax sugar ...Object is used in a constructor / function call to unpack labels:

void main() {
  final a = A(x: 1, y: 2);
  final b = B(...a, z: 3);
  // equivalent to
  final bWithoutSugar = B(x: a.x, y: a.y, z: 3);
}

class A {
  final int x;
  final int y;
  A(this.x, this.y);
}

class B {
  final int x;
  final int y;
  final int z;
  A(this.x, this.y, this.z);

...Object unpack the labels with the intersection between the parameters name and the object getters name.

Copies with null values

The last declaration of the field wins, allowing copying with null values (when the fields are not private).

void main() {
  final a = A(x: 1, y: 2);
  final another = A(...a, y: null);
}

class A {
  final int x;
  final int? y;
  A(this.x, this.y);
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    featureProposed language feature that solves one or more problems

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions