What is the main purpose of the List.single property?

A few days ago, I noticed that the Dart List class has a single property. Then I read the official API document and realized how this property works. This means that I know that List.single works as follows:

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

But I can not find a practical example of using the single property. The baby codes shown above make no sense in real programming, of course.

What is the purpose of ownership? Why does this property throw an exception if the list contains two or more elements? Why is this not a boolean property, which means that List has only one element? How do Dart Language developers find it useful to include List.single in the main API?

If you have any knowledge about this, I would really appreciate it if you give me a hand.

+6
source share
1 answer

You can use single if you expect Iterable to contain only one element. Here is an example of the real world: We have a database connection that has a query method for executing SQL queries. The method returns the rows affected by the request. Now consider a query in which you expect only one row:

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

This gives a short crash path if one or more lines are not affected. Of course, one could 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 it is much longer. Alternatively, you can choose assert .

As List implements Iterable , it also contains single . single getter is also useful for threads if you expect exactly one element. Consider the same example as Stream lines:

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

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


All Articles