Norman
Norman

Reputation: 3167

Dart: declaration behavior of function parameters is different from declaration behavior of local variables

I have this simple function:

void fooFun(int i1, j1) {
  int i2, j2;
  print('${i1.runtimeType}, ${j1.runtimeType}');
}

I would assume that the declared type of the function parameter j1 is int. But when I hover with the mouse cursor over j1 it is displayed as dynamic: Type of function parameter
But j1.runtimeType is (as expected?) anint.
When I declare two variables in the same manner locally (int i2, j2;), the declaration type of the second variable j2 is as expected int.
local variable declaration

This seems a little bit confusing to me:

By the way: I use VSCode as IDE.
I have bundled the three questions above into one post because i think they are very closely related.

Upvotes: 0

Views: 134

Answers (2)

lrn
lrn

Reputation: 71783

Parameter declarations and variable declarations are different, they do not work the same.

Variable declarations are terminated by ;. One variable declaration can declare multiple variables like int i, j;. That's a syntax inherited back (at least) from the C language, and also allowed by Java, C# and JavaScript, the three languages Dart was most inspired by in the beginning.

A parameter declaration is not terminated, but parameter declarations are separated by commas, as a comma separated list. Because of that, it can't also use commas to declare multiple variables in one declaration, so you need to write two declarations, (int i, int j), to declare two parameters. Again, this behavior is (at least) as old as C, and shared by both Java and C# (JavaScript doesn't type variables at all). If you write (int i, j) that is still two separate parameter declarations, the second just defaults to dynamic as type, as if you had written (int i, dynamic j). Other languages may or may not allow you to omit the type.

The declaration defines the type of the variable, which restricts the values which it can contain. Using .runtimeType provides the type of a value, not a variable. The dynamic j variable can contain an integer value, so printing j.runtimeType does not tell you anything about the variable's type.

You can also do print([j].runtimeType); which will print List<dynamic>, telling you that the static/declared type of j is dynamic. (Or declare void logType<T>(T value) { print(T); } and call logType(j);, then type inference will make it logType<dynamic>(j) because the static type of j is dynamic, and it will print "dynamic".)

Upvotes: 3

Your declaration should be: int i1, int j1, because int i1, j1 is interpreted like this int i1, dynamic j1

runtimeType method tries to discover the data type of that object according its data.

Upvotes: 1

Related Questions