What are curly braces that wrap constructor arguments?

Consider the following code snippet:

class Person {
  String id;
  String name;
  ConnectionFactory connectionFactory;

  // What is this constructor doing?
  Person({this.connectionFactory: _newDBConnection});

}

If you precede the constructor argument with this, the corresponding field will be automatically initialized, but why {...}?

+11
source share
2 answers

This makes the argument a named optional argument.

When you create an instance Personyou can

Person p;
p = new Person(); // default is _newDbConnection
p = new Person(connectionFactory: aConnectionFactoryInstance);
  • no {}argument will be required
  • with []argument will be an optional positional argument
// Constructor with positional optional argument
Person([this.connectionFactory = _newDBconnection]);
...
Person p;
p = new Person(); // same as above
p = new Person(aConnectionFactoryInstance); // you don't specify the parameter name

Named optional parameters are very convenient for logical arguments (but, of course, for other cases).

p = new Person(isAlive: true, isAdult: false, hasCar: false); 

, :

  1. () ( )
  2. () ( )

, . : =. , Map ( ).

= Dart 2 , : .

:

+16

this. connectionFactory this. connectionFactory

Person({this.connectionFactory: _newDBConnection});

.

0

Source: https://habr.com/ru/post/1531152/


All Articles