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?
On
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. castFrom(foo): Adapts source (foo) to be a List. Please followfrom(foo): Creates a List from Iterable (foo) objects provided in the Argument. Please follow
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 useList.cast, which will only return a view and will not copy everything from the list. That is a case whenList.castwould 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.castFromas well.As for when should we use
List.frombut not the other two, think about the following case: You have Lista, and want to copy it to listband make some modifications tob. If you only want to modifybbut wantato keep the original, you should useList.fromto copy (clone) instead of theList.cast.In short:
List.castalmost same asList.castFrom. They both do not copy anything. TheList.fromcopies everything.Indeed, you can also look at the source code:
static List<T> castFrom<S, T>(List<S> source) => CastList<S, T>(source);AndCastListis implemented as:So, you can very clearly see that, when you do
cast(orcastFrom), 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.