Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any difference between list.elementAt(n) and list[n]

Tags:

dart

In Dart, is there any difference between accessing list elements using elementAt and the [] operator?

var sensors = ["ir", "ultrasound", "laser"];

void main() {
    print(sensors.elementAt(1));
    print(sensors[1]);
}
like image 604
nbloqs Avatar asked Mar 20 '19 21:03

nbloqs


1 Answers

The .elementAt() method is coming with the Iterable class. It works with all iterables, not only Lists.
Some iterables may have more efficient ways to find the element, so do Lists, using the bracket notation.

What do I mean by more efficient?

The bracket notation will call .elementAt() implicity. The bracket notation does not serve any additional meaning, only ease of use - as many would say, it's a "syntactical sugar". This is what I mean by efficiency. You can use it with less typing. I did not mean algorithmic efficiency, like finding the element faster in a large List or anything like that.

Also, Lists in Dart are similar to the so called "arrays" in many languages. These old-school languages use bracket notation to identify array elements. So the bracket notation is also a tradition and serves the purpose of getting started easily with Dart, when you come from a background of Java or C# ... etc.

like image 80
bradib0y Avatar answered Oct 25 '22 02:10

bradib0y