5

List foo -> List bar
I can use three method

1.List<MyClass> bar = foo.cast<MyClass>()
2.List<MyClass> bar = List.castFrom(foo)
3.List<MyClass> bar = List.from(foo)

What is the difference?

iDecode
  • 22,623
  • 19
  • 99
  • 186
Taz
  • 1,737
  • 1
  • 15
  • 30

2 Answers2

4

The answer to the additional question ("Any practical differences (not just quoting/sharing docs) as to when one would work and the other fail would be appreciated."):

When you have a giant array, copying it (List.from) will not be a smart idea - you will spend a lot of time copying everything and it will also cost you a lot of memory. Instead, you will want to use List.cast, which will only return a view and will not copy everything from the list. That is a case when List.cast would work and other would fail. Indeed, not fail, but not good.

Since "[List.cast is] typically implemented as List.castFrom<E, R>(this)", the example mentioned above applies to List.castFrom as well.

As for when should we use List.from but not the other two, think about the following case: You have List a, and want to copy it to list b and make some modifications to b. If you only want to modify b but want a to keep the original, you should use List.from to copy (clone) instead of the List.cast.

In short: List.cast almost same as List.castFrom. They both do not copy anything. The List.from copies everything.


Indeed, you can also look at the source code: static List<T> castFrom<S, T>(List<S> source) => CastList<S, T>(source); And CastList is implemented as:


abstract class _CastListBase<S, T> extends _CastIterableBase<S, T>
    with ListMixin<T> {
  List<S> get _source;

  T operator [](int index) => _source[index] as T;

...
}

class CastList<S, T> extends _CastListBase<S, T> {
...
}

So, you can very clearly see that, when you do cast (or castFrom), you do not copy and create a new list, but only make a very thin wrapper. That wrapper will make a type cast whenever you use it.

ch271828n
  • 15,854
  • 5
  • 53
  • 88
  • Thanks, I was looking for something like this. I'll give it a read later on – iDecode Sep 10 '21 at 10:37
  • @iDecode You are welcome! Don't forget to award the bounty if you find it useful ;) – ch271828n Sep 10 '21 at 11:39
  • I don't think List.from's cost bigger than List.cast's . List.from don't copy every element to create a new List,that's a shallow cpy,just pointer , same as create a CastList object,latter create a Object and put pointer too. – Oo_oO Jan 12 '23 at 09:33
3
  1. cast<MyClass>: Returns the view (Immutable List, altering order of the list won't be reflected in original list) of the List containing instances of MyClass type. Please follow.
  2. castFrom(foo): Adapts source (foo) to be a List. Please follow
  3. from(foo): Creates a List from Iterable (foo) objects provided in the Argument. Please follow
Zain Ul Abideen
  • 1,617
  • 1
  • 11
  • 25