iDecode
iDecode

Reputation: 28906

Difference between converting a list to a new type using List.from vs List.map?

Say I want to convert following collection to List<int>,

final listDouble = <double>[1.0, 2.0];

I can either use

final listInt = List<int>.from(listDouble);

or

final listInt = listDouble.map<int>((e) => e.toInt()).toList();

Is there any difference between two approaches?

Upvotes: 1

Views: 60

Answers (2)

jamesdlin
jamesdlin

Reputation: 89995

In addition to the laziness mentioned by iDecode's answer, you should be aware that the List<E>.from way isn't technically correct for your case.

List<E>.from requires that the argument list have elements of type E, and ints aren't doubles. (Note that it will work for web platforms (e.g. DartPad), where Dart is transpiled to JavaScript, because all JavaScript numbers are IEEE-754 double-precision floating point numbers. If you try it in a Dart VM, however, it will throw an exception.)

Upvotes: 1

iDecode
iDecode

Reputation: 28906

Yes, there is a difference.

map() returns a lazy Iterable, meaning that the supplied function is called only when the elements are iterated unlike List.from().

Upvotes: 1

Related Questions