0

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?

Reza Shakeri
  • 97
  • 1
  • 12
  • 2
    Does this help? [Difference between casting with 'cast' method and 'as' keyword](https://stackoverflow.com/q/70959115/) – jamesdlin Feb 27 '23 at 20:31
  • @jamesdlin Thanks for the guidance but I saw this link before, but the explanations were unclear to me – Reza Shakeri Feb 27 '23 at 20:35
  • 3
    `.cast` performs a runtime cast for each element of the collection. Can you elaborate about what you're specifically confused about? – jamesdlin Feb 27 '23 at 20:36
  • Yes sure For me, the question is why when we convert a Set of String to a Set Int type does not convert values to int and when we use RuntimeType to understand that value it shows us an error? – Reza Shakeri Feb 27 '23 at 20:44
  • 1
    You cannot cast (whether using `as` or using `.cast`) to convert a `Set` to `Set`. `String` and `int` are not related types. If you want to apply such a conversion, you would need to do: `var intSet = {for (var element in stringSet) int.parse(element)};` or `var intSet = stringSet.map((element) => int.parse(element)).toSet();`. – jamesdlin Feb 27 '23 at 20:48
  • @jamesdlin Thank you really for your good description, I mistakenly thought that when using CAST conversion, the values inside the SET would be converted, but with your explanations I realized that it was not and only the SET type would change and the values remain in the same form, Thank you very much your description helped – Reza Shakeri Feb 27 '23 at 20:52

1 Answers1

4

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.

Abion47
  • 22,211
  • 4
  • 65
  • 88