iDecode
iDecode

Reputation: 29016

What's the benefit of using as when creating an instance, generally inside a factory constructor

class Product {
  final int id;

  Product({this.id});

  factory Product.fromMap(Map<String, dynamic> map) {
    return Product(
      id: map['id'] as int, // Why as?
    );
  }
}

This is a pattern I have seen used by Google, the main question is what's the need of using as there, because below code does the job equally well.

Product(
  id: map['id'], 
)

Can anyone tell me any advantage of using as in above code?

Upvotes: 0

Views: 42

Answers (1)

julemand101
julemand101

Reputation: 31309

This comes down to how the analyzer is configured and if you have disabled implicit-casts in analysis_options.yaml:

analyzer:
  strong-mode:
    implicit-casts: false

The problem in your code is that the type of the map is defined as Map<String, dynamic> so we don't really know the type of the values in the map on compile time. And if we have disabled implicit casting we cannot just assign a dynamic into a int variable without any implicit type casting with as.

It is recommended to use implicit-casts: false (and implicit-dynamic: false) to make the analyzer more strict about your typing which can both make more readable code but only catch errors where you are casting types to other types without your knowing which in the end could have give a runtime error.

There are more about in the documentation: https://dart.dev/guides/language/analysis-options

Upvotes: 1

Related Questions