To clarify, I am asking about the design decisions of the language and the internal workings of the compiler and executor.
In Dart, there are three conditions for creating a const object from a class:
- The constructor should be a const constructor
- Every attribute of the class should be final
- The constructor should not have a body
P.S. : I am going to self-answer this question. But I would appreciate if you can read my answer and tell me if it is wrong or add information that I did not know
Although not directly a part of my question, I am attaching below the series of tests that I did to undestand the language with respect to this question: https://docs.google.com/document/d/1Y8IlOlzI5VGFLzLFlih1d7QgOdynUxvrF7Q3kd0OSwQ/edit?usp=sharing
My hypotheses:
We know that Dart creates different constructors for creating const and non-const objects (even constructors marked as const internally have a non-const copy). The compiler could’ve been made to create a const constructor on its own when it encounters a const object creation, but this leads to redundancy (both time and memory-wise) because of issues pertaining to the code segment memory allocation to the class and pre-compiled header files. So it is better for the class itself to mark the constructor as a const constructor, and hence the rule 1.
Restrictions on modifying attributes, is handled in the form of removing their setter methods. Methods are common for the class, and can not be separated between const and non-const objects without creating different versions of the class. Although, this is likely possible for the compiler to implement internally, Dart perhaps chose the simple approach of leveraging existing mechanisms, which results in rule 2. Because a final attribute does not have a setter method, whether the class has a const constructor or not.
For rule 3, There are two reasons why we might want to have a body for a constructor:
When neither of the use cases is applied (and both cases require additional work to implement, as normally in languages the constructor body is executed after creating the object), why even allow a body? If at all, we need something to be run from the object, we can do it at runtime with class methods (not the constructor)