so why didn’t they change the definition of creating a new instance which can be created
const
simply asconst
instead ofnew
?
If you mean why doesn’t final a = A();
automatically assume const A()
if A
has a const
constructor:
-
Sometimes it is automatic:
const a = A();
in which case
A
‘s constructor is being invoked in aconst
context and doesn’t need an extraconst
qualifier on the right-hand-side. -
An explicit
const
expresses intent. For example, suppose you had:final a = A(B());
where
A
andB
haveconst
constructors. Later, somebody makes a change:final a = A(C());
where
C
does not have aconst
constructor. Ifconst
were automatic, then you would have no idea thata
is no longerconst
. Maybe that’s okay, but it also could suddenly have a negative impact on your application’s performance, and without an explicitconst
qualifier, the impact of a local change could have a much wider scope than expected. (That said, explicitconst
qualifiers and automatically adding them aren’t mutually exclusive.) -
const
can have downsides.const
creates compile-time constants. If you have:final a1 = A(); final a2 = A();
identical(a1, a2)
is not true. Ifconst A()
were implicit, thenidentical(a1, a2)
would be true, and maybe that’s not a property that the code intended to have. -
Compile-time constants live forever. The whole point is to have an object that can be reused instead of re-constructing it. The flipside is that won’t be destroyed.