java 构造函数后面大括号,大括号括起来的构造函数参数代表什么?

Consider the following piece of code:

class Person {

String id;

String name;

ConnectionFactory connectionFactory;

// What is this constructor doing?

Person({this.connectionFactory: _newDBConnection});

}

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

解决方案

This makes the argument a named optional argument.

When you instantiate a Person you can

Person p;

p = new Person(); // default is _newDbConnection

p = new Person(connectionFactory: aConnectionFactoryInstance);

without {} the argument would be mandatory

with [] the argument would 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 boolean arguments (but of course for other cases too).

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

There is a specific order in which these argument types can be used:

mandatory (positional) arguments (only positional arguments can be mandatory)

optional positional arguments

(optional) named arguments (named arguments are always optional)

Note that positional and named optional arguments use a different delimiter for the default value.

The named requires : but the positional requires =. The language designers argue that the colon fits better with the Map literal syntax (I would at least have used the same delimiter for both).

= is supported as delimiter since Dart 2 and preferred according to the style guide while : is still supporzed.

See also:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值