Home > Net >  Explict generic type in function by default replace this type to dynamic inside
Explict generic type in function by default replace this type to dynamic inside

Time:05-07

Why explict generic type in function by default replace this type to dynamic inside?

example:

class Boo {
  void displayType<int>() {
    print('type int to string: $int');
    print('type string to string: $String');
  }
}

main() {
  final boo = Boo();
  boo.displayType();
}

output:

type int to string: dynamic
type string to string: String

its bug?

CodePudding user response:

name of generic can be existing type. So if tell any type in function, inside int can be any another type

main() {
  final boo = Boo();
  boo.displayType<Boo>();
}
type int to string: Boo
type string to string: String

CodePudding user response:

Here <int> is not an int data type but a name of generic datatype to be passed into function.

void displayType<int>() {
    print('type int to string: $int');
    print('type string to string: $String');
  }

Compliler builds priorities from global to local. That means - it will prioritize local variables, arguments, generic types more than global ones. For example:

int number = 2;
void someFunc(){
  //local variables are in higher priorities inside their closures
  int number = 3;
  //will print 3
  print(number);
}

You definded generic type as <int> - compiler takes it as a priority in assgning and usage operations above the actual data type named int. Knowing this - do not be confused and make generic types consisting of 1 letter as usually it is done in many documentations.

   void displayType<T>() {
    //now it prints int
    print('type int to string: $int');
    //will print dynamic
    print('type generic to string: $T');
    print('type string to string: $String');
  }
  main() {
  final boo = Boo();
  boo.displayType();
}
  •  Tags:  
  • dart
  • Related