Home > Net >  why the second short form constructor gives the error that name and age must be initialized but not
why the second short form constructor gives the error that name and age must be initialized but not

Time:05-07

I am beginner in dart language. So i created this class ..

class X{
  String name;
  int age;
  // X(this.name,this.age); 
  X(name,age);
}

In this code the short form ctor X(name,age) gives error that name and age must be initilized but the ctor X(this.name,this.age) doesnt give such error.

In ctor X(this.name,this.age) compiler know that name and age will surely be initilized.. but in ctor X(name,age) why compiler cannot do that....(isn't it obvious that name and this.name is same thing).

please elaborate....

CodePudding user response:

In Dart, if you don't specify any type, the language will assume you mean dynamic in this case.

So what your code is actually doing is:

class X{
  String name;
  int age;

  X(dynamic name, dynamic age);
}

The problem then becomes that we don't assign these parameters to anything in the class since the name in the constructor would be a different name than the name in the class definition.

The analyzer would therefore complain about name and age not being provided a value since both fields are defined with non-nullable types and can therefore not be null (which is the default value for any variable in Dart regardless of its type).

The this.name and this.age is a shortcut to the following code:

class X{
  String name;
  int age;

  X(String name, int age) : name = name, age = age;
}

The name = name works because we are not allowed to set the parameter to some other value in the initializer part of the constructor. So Dart can assume that the first name must mean the class variable while the second name means the parameter, since the parameter is the one closest in scope.

  •  Tags:  
  • dart
  • Related