Home > Net >  Is it bad practice to use var keyword in Dart
Is it bad practice to use var keyword in Dart

Time:04-12

I am using var keyword often. But I read that if I use var keyword, this variable allocates much space as it can. So if I declare integer like int a = 1; will my program be performant than var a = 1; ? Is this information are true? I searched it but didn't find any results about this. I know it is a stupid question but i'm confused.

CodePudding user response:

There is absolutely no difference between writing int a = 1; and var a = 1;.

In the latter case, type inference is applied, by the compiler, to infer the declared type of the variable. The inferred type is taken from the type of the initializing expression, which is an int, so after type inference, var a = 1; becomes int a = 1;.

There are places where using var is unnecessary (function arguments, like int foo(var x) => x.toString().length;, where the var is unnecessary and can be removed), and places where it's not going to give you what you want (double x = 1; does not mean the same as var x = 1; because the latter infers a the variable to have type int, and the former infers 1 to be a double literal.)

In most cases, using var is fine. The style guide even recommends it over the redundant int x = 1;.

CodePudding user response:

Not a stupid question at all, the use of int a = 1 or string a = "one" is wise when knowing what value you will be dealing with - every variable has a job, when you know what indefinitely you'll be working with integers, strings, doubles, floats, booleans, etc. it is recommended practice to declare the appropriate type (down the line it pays off as you debug as well, most IDEs assist when coding with specific variable types, more readable, more information) - the use of var a = 1, or 'var' in general is when you don't exactly know what the job of the variable will be, as in it could store anything from a boolean true/false, or maybe a number, or maybe a string of characters - by declaring it as a universal variable you are basically giving it the type of possibly anything. It's not "wrong", but not ideal either if you know exactly what you are working with - that's why we have all these unique variable types.

  •  Tags:  
  • dart
  • Related