Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Dart, can you call another constructor from a constructor

That is, I'm trying to invoke one constructor from another, and then construct further. I can't figure out from documentation if it can be done.

Here's a contrived example, in case it helps:

class Chipmunk {    Chipmunk.named(this.name);    Chipmunk.famous() {     this.named('Chip');  // <-- What, if anything, goes here?     this.fame = 1000;      } }  var chip = new Chimpmunk.famous(); 
like image 421
Grumdrig Avatar asked Nov 16 '13 05:11

Grumdrig


People also ask

Can you call another constructor from a constructor?

The keyword “this” is used to call a constructor from within another constructor in the same class. The keyword “super” is used to call the parent (super) class constructor from within child (subclass) class constructor.

Can constructors call each other?

You can call another constructor via the this(...) keyword (when you need to call a constructor from the same class) or the super(...) keyword (when you need to call a constructor from a superclass). However, such a call must be the first statement of your constructor.

Can a constructor call another constructor using this keyword?

From within a constructor, you can also use the this keyword to call another constructor in the same class. Doing so is called an explicit constructor invocation.


1 Answers

There are two possible ways to do this:

class Chipmunk {   String name;   int fame;    Chipmunk.named(this.name, [this.fame]);    Chipmunk.famous1() : this.named('Chip', 1000);   factory Chipmunk.famous2() {     var result = new Chipmunk.named('Chip');     result.fame = 1000;     return result;   } } 

Chipmunk.famous1() is a redirective constructor. You can't assign properties in this one, so the constructor you are calling has to allow all the properties you want to set. That's why I added fame as an optional parameter. In this case you could make name and fame final.

Chipmunk.famous2() is a factory constructor and can just create the instance you want. In this case, fame couldn't be final (obviously it could be if you used the fame parameter in the named constructor).

The first variant would probably be the preferable one for your use case.

This is the documentation in the language spec:

A generative constructor consists of a constructor name, a constructor parameter list, and either a redirect clause or an initializer list and an optional body.

https://www.dartlang.org/docs/spec/latest/dart-language-specification.html#h.flm5xvbwhs6u

like image 69
Dennis Kaselow Avatar answered Sep 20 '22 08:09

Dennis Kaselow