Valentin Vignal
Valentin Vignal

Reputation: 8172

How to access the attribute from a constant constructor in the constructor initialiser list?

I am having trouble understanding how constant constructors and the constructor initializer list in dart.

I have this small code:

class A {
  const A();
}

class B {
  const B();

  final A a = const A();
}

class C {
  const C(): a = const A();

  final A a;
}

class D {
  const D(): b = const B();

  final B b;
}

class E {
  const E(): a = const B().a;  // <- Lint: Invalid constant value

  final A a;
}

All of these classes and their constructors are legit. Except for E and E() constructor.


What I don't understand is that the D constructor is valid:

const C(): a = const A();

But E is not valid:

const E(): a = const B().a;  // <- Lint: Invalid constant value

It kind of confuses me, why does B() can be a constant value and B().a is not? I would have thought if an object is a constant constructor, B().a would have been a constant value too.

What am I missing here?

Upvotes: 2

Views: 251

Answers (1)

jamesdlin
jamesdlin

Reputation: 89965

It kind of confuses me, why does B() can be a constant value not B().a is not? I would have thought if an object is a constant constructor, B().a would have been a constant value too.

Dart does not have an equivalent of constexpr like in C++. Dart has no way of conveying that methods/functions can be computed and invoked as compile-time constant expressions.

B().a invokes a getter named a on B(). Just because const B() is a const object does not mean that const B().a returns a constant value. For example, B's implementation could be:

class B {
  const B();

  // Returns a new `A` instance each time.
  A get a => A();
}

Upvotes: 3

Related Questions