Home > Mobile >  Is "dynamic" a data type in Dart?
Is "dynamic" a data type in Dart?

Time:06-13

I have read that dynamic is a data type in Dart, but is it correct to call it a data type? it doesn't seems like a data type, it seems like it is a way to allow your variable to be of any data type.

CodePudding user response:

In Dart, dynamic is a type. It belongs in the type hierarchy and is related to other types by the subtype relation.

It's a "top" type, which means that every type is a subtype of dynamic. (Including itself, because the "subtype" relation is reflexive - every type is considered a subtype of itself, and the term "proper subtype" is used when only talking about subtypes that are not also supertypes.)

Being a top type, it means any value can be assigned to a variable of type dynamic. So can they to any other top type, which mainly means Object?. The difference between the two is that:

  • An expression with static type dynamic can be assigned to any type. That's obviously unsafe, so the runtime inserts a check, a so called "implicit downcast" which works just like doing as TargetType.
  • You can call any member on an expression with static type dynamic. That's obviously unsafe, so the runtime will throw if the object doesn't have such a member.

That kind of runtime checked unsafe behavior (not static type-checked) is the reason the type is named dynamic. Using dynamic is a way to turn off the static type system. Use with extreme care.

Whether you can call dynamic a "data type" depends on what you mean by "data type". The Dart language specification doesn't use the term "data type" about anything.

CodePudding user response:

Yes. The specifications call it a type (https://www.ecma-international.org/publications-and-standards/standards/ecma-408/)

The type dynamic denotes the unknown type. If no static type annotation has been provided the type system assumes the declaration has the unknown type

Type dynamic has methods for every possible identifier and arity, with every possible combination of named parameters. These methods all have dynamic as their return type, and their formal parameters all have type dynamic. Type dynamic has properties for every possible identifier. These properties all have type dynamic

  •  Tags:  
  • dart
  • Related