Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I initialize a final field in constructor's body?

Tags:

dart

Basically, that's what I'm trying to do:

  ClassName   {     final OtherClass field;      ClassName()     {       field = new OtherClass(this);     }   } 
like image 446
Max Yankov Avatar asked Nov 05 '13 18:11

Max Yankov


People also ask

Can a final variable be initialized in method?

A final variable can only be initialized once, either via an initializer or an assignment statement.

How do you initialize a dart function?

Either declare the function as static in your class or move it outside the class altogether. If the field isn't final (which for best practice, it should be, unless the field has to mutate), you can initialize it using a regular non-static method in the constructor body.


1 Answers

It's not possible to assign a final field in a constructor body. The final field needs to be assigned before the constructor body, in the initializer list or on declaration:

class ClassName {     final OtherClass field = new OtherClass(); // Here      ClassName()         : field = new OtherClass() // or here      {           } } 

As you can't use this in the initializer list or on the declaration, you can't do what you plan to do.

like image 162
Fox32 Avatar answered Sep 20 '22 01:09

Fox32