ThePiercingPrince
ThePiercingPrince

Reputation: 1921

How to explicitly specify variables as type dynamic?

dynamic x = 2;

This doesn't compile. But:

final int n = 6; /* and */
final y = "Hello world!"

both compile.

Is it possible and how to declare variables explicitly as of type dynamic?

Upvotes: 2

Views: 149

Answers (2)

Ganymede
Ganymede

Reputation: 3665

It is possible to declare variables explicitly as being type dynamic. The code

dynamic x = 2;

compiles and is equivalent to the code

var x = 2;

var is shorthand for dynamic when declaring variables. Omitting a type annotation is equivalent to making the type annotation dynamic.

The difference between var and dynamic is that var is for declaring variables and is not a type; it cannot be the return type of a function (since that is not declaring a variable) and function arguments can omit the keyword var (the declaration f(x){} is equivalent to the declarations f(dynamic x){} and f(var x){}).

You only need to explicitly use dynamic in type parameters for generic classes where at least one but not all type parameters are dynamic, such as Map<String, dynamic>.

Upvotes: 3

MarioP
MarioP

Reputation: 3832

var x = 2; defines a variable without explicit type, which is the same as dynamic.

Upvotes: 1

Related Questions