Peter StJ
Peter StJ

Reputation: 2417

dart: what is the meaning of class constructor being marked as const

So I have seen code as such:

class Whatever {
  final String name;
  const Whatever(this.name);
}

What does change by the fact that the constructor is marked with const? Does it have any effect at all?

I have read this:

Use const for variables that you want to be compile-time constants. If the const variable is at the class level, mark it static const. (Instance variables can’t be const.)

but it does not seem to make sense for the class constructor.

Upvotes: 14

Views: 6155

Answers (1)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 658087

  • The constructor can't have a constructor body.
  • All members have to be final and must be initialized at declaration or by the constructor arguments or initializer list.
  • You can use an instance of this class where only constants are allowed (annotation, default values for optional arguments, ...)
  • You can create constant fields like static const someName = const Whatever();

If the class doesn't have a const constructor it can't be used to initialize constant fields. I think it makes sense to specify this at the constructor. You can still create instances at runtime with new Whatever() or add a factory constructor.

See also

The "old style" (still valid) enum is a good example how to use const https://stackoverflow.com/a/15854550/217408

Upvotes: 16

Related Questions