1

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?

0

2 Answers 2

1

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.)

Sign up to request clarification or add additional context in comments.

5 Comments

Yes, you're right, I should have converted the list from double to int, in that case it would work, correct?
@iKeepChangingName It doesn't matter whether you convert from double to int or int to double. Neither derives from the other, so they aren't implicitly convertible.
Ok, in that case, I'd like a like a little more explanation of your line List<E>.from requires that the argument list have elements of type E?
I don't know how I can explain it any more; it means exactly what it says. List<int>.from requires that the argument already be a collection of ints. List<int>.from is basically the same as List<int>.of except .from is from before Dart had compile-time type-checking, so .from will fail at runtime if the argument type is wrong.
I accepted your answer because of your detailed explanation. Thank. you
1

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().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.