I hope you are fine,
I read about the Set<R> cast<R>()
method in Dart's documentation, but I was unaware of both his description and his application
can anyone explain more complete and understandable?
I hope you are fine,
I read about the Set<R> cast<R>()
method in Dart's documentation, but I was unaware of both his description and his application
can anyone explain more complete and understandable?
Generic collections in Dart are always typed by the data they can contain, such as List<int>
, Set<String>
, or Map<dynamic, dynamic>
. This is all well and good, but because of how generics work in Dart, you can't always simply cast a collection of one type into another type. For example, this code will throw an error at runtime:
List<dynamic> foo = [1, 2, 3];
List<num> bar = foo as List<num>; // Error: List<dynamic> is not a subtype of List<num>
Instead, we have cast
methods, which instead of casting the entire collection, will loop through the collection casting all of the elements within to the desired type, resulting in a collection of that type.
List<dynamic> foo = [1, 2, 3];
List<num> bar = foo.cast<num>();
Note that, like a normal cast, the cast
method will throw an error if any of the elements in the collection aren't compatible with the target type.