简体   繁体   English

List.single属性的主要用途是什么?

[英]What is the main purpose of List.single property?

Some days ago, I noticed that Dart's List class has the single property. 几天前,我注意到Dart的List类具有single属性。 Then, I read an official API document, and understood how this property works. 然后,我阅读了官方API文档,并了解了此属性的工作原理。 This mean I know that List.single works as follows: 这意味着我知道List.single工作原理如下:

print(['a'].single);     // outputs 'a'
print(['a', 'b'].single) // throws StateError

But I cannot find any practical use case of the single property. 但我找不到single财产的任何实际用例。 Childish codes showed above make no sense in actual programming, of course. 当然,上面显示的幼稚代码在实际编程中毫无意义。

What is the purpose of the property? 该物业的目的是什么? Why does this property throw an Exception if a List contains two or more elements? 如果List包含两个或更多元素,为什么此属性会抛出异常? Why is it not a boolean property which stands for whether a List has only single element? 为什么它不是一个布尔属性,它代表List是否只有单个元素? How do Dart Language developers think it is useful to include List.single in the core API? Dart语言开发人员如何认为将List.single包含在核心API中是有用的?

If you have any knowledge about this, I would appreciate it very much if you give me a hand. 如果您对此有任何了解,如果您帮助我,我将非常感激。

You can use single in case you expect an Iterable to only contain one element. 如果您希望Iterable只包含一个元素,则可以使用single Here is a real world example: We have database connection that has query method to execute a SQL queries. 这是一个真实世界的例子:我们有数据库连接,它具有执行SQL查询的query方法。 The method returns the rows affected by the query. 该方法返回受查询影响的行。 Now consider a query where you only expect exactly one line to be affected: 现在考虑一个查询,您只希望影响一行:

var row = databaseConnection.query('SELECT * FROM xyz WHERE id=5').single;

This gives a short way of failing in case no or more then one line are affected. 如果没有或多于一行受到影响,这会给出一种简短的失败方式。 Sure, one could also write: 当然,还可以写:

var rows = databaseConnection.query('SELECT * FROM xyz WHERE id=5');

if (rows.length != 1) {
  throw new StateError('Something is wrong');
}

var row = rows.first;

But this is much longer. 但这要长得多。 Alternatively you may want to assert . 或者你可能想要assert

As List implements Iterable , it also contains single . 由于List实现了Iterable ,它也包含single The single getter is also useful for streams, if you expect exactly one element. 如果你只想要一个元素,那么single getter对于流也很有用。 Consider the same example as a Stream of rows: 考虑与行Stream相同的示例:

databaseConnection.query('SELECT * FROM xyz WHERE id=5').single.then((row) {
  print('Process the row');
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM