Difference between "var" and "dynamic" type in Dart? - dart

According to this article:
As you might know, dynamic (as it is now called) is the stand-in type when a static type annotation is not provided.
So, what is the difference between dynamic and var? When to use?

dynamic is a type underlying all Dart objects. You shouldn't need to explicitly use it in most cases.
var is a keyword, meaning "I don't care to notate what the type is here." Dart will replace the var keyword with the initializer type, or leave it dynamic by default if there is no initializer.
Use var if you expect a variable assignment to change during its lifetime:
var msg = "Hello world.";
msg = "Hello world again.";
Use final if you expect a variable assignment to remain the same during its lifetime:
final msg = "Hello world.";
Using final (liberally) will help you catch situations where you accidentally change the assignment of a variable when you didn't mean to.
Note that there is a fine distinction between final and const when it comes to objects. final does not necessarily make the object itself immutable, whereas const does:
// can add/remove from this list, but cannot assign a new list to fruit.
final fruit = ["apple", "pear", "orange"];
fruit.add("grape");
// cannot mutate the list or assign a new list to cars.
final cars = const ["Honda", "Toyota", "Ford"];
// const requires a constant assignment, whereas final will accept both:
const names = const ["John", "Jane", "Jack"];

dynamic: can change TYPE of the variable, & can change VALUE of the variable later in code.
var: can't change TYPE of the variable, but can change VALUE of the variable later in code.
final: can't change TYPE of the variable, & can't change VALUE of the variable later in code.
dynamic v = 123; // v is of type int.
v = 456; // changing value of v from 123 to 456.
v = 'abc'; // changing type of v from int to String.
var v = 123; // v is of type int.
v = 456; // changing value of v from 123 to 456.
v = 'abc'; // ERROR: can't change type of v from int to String.
final v = 123; // v is of type int.
v = 456; // ERROR: can't change value of v from 123 to 456.
v = 'abc'; // ERROR: can't change type of v from int to String.

try this in DartPad:
void main() {
dynamic x = 'hal';
x = 123;
print(x);
var a = 'hal';
a = 123;
print(a);
}
you can change the type of x, but not a.

var, like final, is used to declare a variable. It is not a type at all.
Dart is smart enough to know the exact type in most situations. For example, the following two statements are equivalent:
String a = "abc"; // type of variable is String
var a = "abc"; // a simple and equivalent (and also recommended) way
// to declare a variable for string types
On the other hand, dynamic is a special type indicating it can be any type (aka class). For example, by casting an object to dynamic, you can invoke any method (assuming there is one).
(foo as dynamic).whatever(); //valid. compiler won't check if whatever() exists
(foo as var).whatever(); //illegal. var is not a type

var a ;
a = 123;
print(a is int);
print(a);
a = 'hal';
print(a is String);
When defined without initial value, var is dynamic
var b = 321;
print(b is int);
print(b);
//b = 'hal'; //error
print(b is String);
When defined with initial value, var is int in this case.

To clarify some of the previous answers, when you're declaring a variable as dynamic, it's type changes depending on what you assign to it. When you're declaring a var, the type is set once it's assigned something, and it cannot be changed after that.
For example, the following code:
dynamic foo = 'foo';
print('foo is ${foo.runtimeType} ($foo)');
foo = 123;
print('foo is ${foo.runtimeType} ($foo)');
will return the following result when run in DartPad:
foo is String (foo)
foo is int (123)
But the following code won't even compile:
var bar = 'bar';
print('bar is ${bar.runtimeType} ($bar)');
bar = 123; // <-- Won't compile, because bar is a String
print('bar is ${bar.runtimeType} ($bar)');
Long story short - use dynamic if you want a non-typed variable, use var when you want a typed variable with whatever type you assign to it.

Looking at the previous answers I hope this can clarify/summarize everything:
There are the keywords var, final, and const. These are to declare a variable (to indicate its existence) (Side note: Declaration vs Initialization)
Then there are types like String, int, List, dynamic, etc. (The type indicates what kind of value the variable should hold, this is for type safety)
Usually, we declare a variable by explicitly stating its type:
String a; // a is now a String type
int b; // b is now an int type
But we can also use the var keyword. By default, this sets the type of the variable to whatever it is initialized with. (This is called type inference)
var a = "hello"; // a is now a String type
var b = 5; // b is now an int type
Now what happens when you try to declare a variable with the var keyword, but don't initialize a value? How is it supposed to infer a type? Well, there is also a type called dynamic. This is different than the usual String or int in the sense that it allows for the variable to be assigned a value of any type (Usually there will be an error).
String a = "hello"; // a is now a String type
// var a = "hello"; // Alternative way; same as the line above because its type is inferred to be String
a = 5 // error: A value of type 'int' can't be assigned to a variable of type 'String'
dynamic b; // b is now a dynamic type
b = "hello"; // still a dynamic type, but now its value is of type String (You can use b.runtimeType to check)
b = 5; // dynamic type, but now its value is of type int
So to address the original confusion regarding the quote from the article,
As you might know, dynamic (as it is now called) is the stand-in type when a static type annotation is not provided.
It just means that if you don't explicitly state its type (you use var to declare a variable) and do so without initialization, it simply infers its type as dynamic:
var b; // b is now a dynamic type, the following will not have any errors.
b = "hello";
b = 5;
b = true;
Other notes:
Not sure why people started talking about final and const, but I think the accepted answer here explains it well if you want to know more.
dynamic a; and var a; is effectively the same: They both declare a variable of dynamic type.
Two ways of checking the type of a variable is using the is operator and using .runtimeType which works differently. See the following example:
dynamic b; // b is now a dynamic type, no value
print(b is dynamic); // true
print(b is Null); // true
print(b is String); // false
print(b is int); // false
print(b.runtimeType); // Null
b = "hello"; // dynamic type, String value
print(b is dynamic); // true
print(b is Null); // false
print(b is String); // true
print(b is int); // false
print(b.runtimeType); // String
b = 5; // dynamic type, int value
print(b is dynamic); // true
print(b is Null); // false
print(b is String); // false
print(b is int); // true
print(b.runtimeType); // int

One of aspect than can consider in comparison dynamic vs var is taking into account behavior when using var declaration with initialization at the same time there is not possibility to change type which in case of dynamic is.
But dynamic vs var is not the question what I would ask.
I would ask more what is difference between dynamic vs Object.
Here is a DO annotate with Object instead of dynamic to indicate any object is allowed.
It is hard to feel it at the beginning, but dynamic I would relate to generic type argument.

Both in dynamic and var,the variable can hold data of any data type, i.e., int , float,string,etc
If a variable is declared as a dynamic and if even initialised, its type can change over time.Try this code in https://dartpad.dev/
void main() {
dynamic x = 'abc';
x = 12345;
print(x);
}
If you declare variable as a var, once assigned type can not change.
void main() {
var x = 'abc';
x = 12345;
print(x);
}
The above code will result in the error stating that A value of type 'int' can't be assigned to a variable of type 'String' - line 3
BUT, if you state a var without initializing, it becomes a dynamic:
void main() {
var x ;
x = 'abc';
x=12345;
print(x);
}

A dynamic variable can change his type and a var type can't be changed.
For example :
var myVar = 'hello';
dynamic myDynamicVar = 'hello';
myVar = 123; // not possible
myDynamicVar = 123; // possible

dynamic is a data type that indicates all data types in dart
var is a variable declaration way like "final" that takes the data type of its value

If you use var you can't change the data type of the variable. But if you use dynamic you can change it freely.
for ex.
dynamic x = 12; // type: integer
x= "Hello world"; // type: string
This will work with no issues if you do the same using var instead of dynamic you will get an error since you can't change the data type because it is automatically assigned to the variable when initialized.

dynamic: can change the TYPE of the variable, & can change the VALUE of the variable later in the code.
var: can't change the TYPE of the variable, but can change the VALUE of the variable later in code

Related

What is the use of constant values in dart?

As described in the documentations:
The const keyword isn’t just for declaring constant variables. You can also use it to create constant values, as well as to declare constructors that create constant values. Any variable can have a constant value.
Can someone explain the use of constant values?
This is a simple example which I hope explains clearly:
Start with two variables and a constant.
var foo = [10,11];
var bar = const [20,21];
const baz = [30,31];
Try to modify foo and it succeeds.
foo.add(12); // [10,11,12]
Try to similarly modify bar and there's an error, because even though bar is a variable, its value was declared to be a constant, thus is immutable.
bar.add(22); // ERROR!
Try to reassign bar to a different value. That works since bar itself was not declared as a constant.
bar = [40,41];
Now, try to modify bar's value again and this time it works, since its new value is not a constant.
bar.add(42) // [40,41,42]
Try to modify baz and there's an error, since baz being declared as a constant itself, its value is inherently immutable.
baz.add(32); // ERROR!
Try reassigning baz to a new value and it fails because baz is a constant and can't be reassigned to a new value.
baz = [50,51]; // ERROR!
void main() {
simpleUse();
finalUse();
constUse();
}
simpleUse() {
print("\nsimple declaration");
var x = [10];
print('before: $x');
x = [5];//changing reference allowed
x.add(10);//changing content allowed
print('after: $x');
}
finalUse() {
print("\nfinal declaration");
final x = [10];
print('before: $x');
// x = [10,20]; //nope changing reference is not allowed for final declaration
x.add(20); //changing content is allowed
print('after: $x');
}
constUse() {
print("\nconst declaration");
const x = [10];
print('before: $x');
// x = [10,20]; //nope -> changing reference is not allowed for final declaration
// x.add(20);//nope -> changing content is not allowed
print('after: $x');
}
Also, variables are simple values like x = 10;
values are instances of enums, list, maps, classes, etc.
I want to add, that another point for const is to guarantee your get the same instance of the object each time you construct it with the same parameters:
class Test {
final int value;
const Test(this.value);
}
void main() {
print(Test(5).hashCode == Test(5).hashCode); // false
print((const Test(5)).hashCode == (const Test(5)).hashCode); // true
}
This is the reason why the const constructor can be difficult to make for all objects since your need to make sure the object can be constructed on compile-time. Also, why after creation of the object no internal state can be changed as the previous answer also shows.

Cannot assign to a parameter

I have declared a function
func someFunction(parameterName: Int) {
parameterName = 2 //Cannot assign to let value parameter Name
var a = parameterName
}
and trying to assign it a value during runtime, but it gives me error
"Cannot assign to let value parameter Name".
Is the parameter name constant by default? Can I change it to a variable?
[In Swift >= 3.0] Function parameters are defined as if by let and thus are constants. You'll need a local variable if you intend to modify the parameter. As such:
func someFunction (parameterName:Int) {
var localParameterName = parameterName
// Now use localParameterName
localParameterName = 2;
var a = localParameterName;
}
[In Swift < 3.0] Declare the argument with var as in:
func someFunction(var parameterName:Int) {
parameterName = 2;
var a = parameterName;
}
use of inout has a different semantics.
[Note that "variable parameters" will disappear in a future Swift version.] Here is the Swift documentation on "variable parameters":
Function parameters are constants by default. Trying to change the
value of a function parameter from within the body of that function
results in a compile-time error. This means that you can’t change the
value of a parameter by mistake.
However, sometimes it is useful for a function to have a variable copy of a parameter’s value to work with. You can avoid defining a
new variable yourself within the function by specifying one or more
parameters as variable parameters instead. Variable parameters are
available as variables rather than as constants, and give a new
modifiable copy of the parameter’s value for your function to work
with.
Define variable parameters by prefixing the parameter name with the keyword var: ..."
Excerpt From: Apple Inc. “The Swift Programming Language.”
If you actually want to change the value stored in a location that is passed into a function, then, as #conner noted, an inout parameter is justified. Here is an example of that [In Swift >= 3.0]:
1> var aValue : Int = 1
aValue: Int = 1
2> func doubleIntoRef (place: inout Int) { place = 2 * place }
3> doubleIntoRef (&aValue)
4> aValue
$R0: Int = 2
5> doubleIntoRef (&aValue)
6> aValue
$R1: Int = 4
In order to modify the argument passed in, you have to designate it as an inout parameter:
func someFunction(inout parameterName:Int)
{
parameterName = 2;
var a = parameterName;
}
Note this will change the variable that was passed in as well. If that isn't what you're looking for, use var as GoZoner suggested.

Why is TextFormat.color not a Number?

var tf:TextFormat = myTextField.getTextFormat();
trace(typeof tf.color); // "number"
trace(tf.color is uint); // true
var myColor:uint = tf.color; // error: 1118: Implicit coercion of a value with static type Object to a possibly unrelated type Number.
Why?
var myColor:uint = int(tf.color); // works. But why do I have to cast it?
From Adobe's API reference:
color:Object
So color is type of Object, the second line traced out number as type because it was assigned by default or in code, but it does not necessarily mean that color can only be number. We can assign string type to color object as well, so type of tf.color can be a number or a String:
tf.color = "0x00ff00";
myTextField.setTextFormat(tf); // Change text color to green
If we compare the following two lines:
var myColor:uint = "0x00ff00"; // 1067: Implicit coercion of a value of type String to an unrelated type uint.
var myColor:uint = tf.color; // 1118: Implicit coercion of a value with static type Object to a possibly unrelated type Number.
// var myColor:uint = new Object(); // This line gives same 1118: Implicit coercion of a value with static type Object to a possibly unrelated type uint.
We can see that the compiler is complaining that it needs explicit instructions to perform the conversion. From this point, we have enough reason to believe that the compiler is designed the way it is. Also notice that you can use constructor of uint or int to convert Object to number. uint and int are both derived classes of Object.
var myColor:uint = new uint(tf.color);
I hope this shed light.

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?
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>.
var x = 2; defines a variable without explicit type, which is the same as dynamic.

Why Array.zeroCreate still fills null for non nullable type?

Does it imply that whenever I am passed an array of a non nullable type, I should still check if it is null? Actually it is not even possible to check <> null but have to use operator.unchecked .How is it better than C#?
type test=
{
value: int
}
let solution = Array.zeroCreate 10
solution.[0] <- {value = 1}
solution.[1].value // System.NullReferenceException: Object reference not set to an instance of an object
type test =
{value: int;}
val solution : test [] =
[|{value = 1;}; null; null; null; null; null; null; null; null; null|]
val it : unit = ()
It depends where the array is being passed from.
If the array is created and used only within F#, then no, you don't need to check for null; in fact, you shouldn't check for null (using Unchecked.defaultOf) because the F# compiler optimizes some special values like [] (and None, in certain cases) by representing them as null in the compiled IL.
If you're consuming an array being passed in by code written in another language (such as C#), then yes, you should still check for null. If the calling code just creates the array and doesn't mutate it any further, then you'll only need to perform the null checks once.
EDIT : Here's a previous discussion about how the F# compiler optimizes the representation of certain values using null: Why is None represented as null?
As the documentation for Array.zeroCreate indicates, it initializes the elements to Unchecked.defaultof<_>. This therefore carries with it all of the same caveats that direct use of Unchecked.defaultof does. Generally, my advice would be to use Array.create/Array.init whenever possible, and to treat Array.zeroCreate as a possible performance optimization (requiring care whenever dealing with non-nullable types).
You're creating a record type, which is implemented as a class, which is indeed nullable. If you intended to create a struct, your code should look something like this:
type test =
struct
val value: int
new(v) = { value = v }
override x.ToString() = x.value.ToString()
end
let solution = Array.zeroCreate 10
solution.[0] <- test(1)
This outputs: val solution : test [] = [|1; 0; 0; 0; 0; 0; 0; 0; 0; 0|]
You could also write the type using the Struct attribute, saving you a level of indentation.
[<Struct>]
type test =
val value: int
new(v) = { value = v }
override x.ToString() = x.value.ToString()

Resources