...

/

Should a Parameter be const or immutable?

Should a Parameter be const or immutable?

This lesson explains when a parameter should be const and when it should be immutable.

We'll cover the following...

Our discussion so far shows that because they are more flexible, const parameters should be preferred over immutable parameters. This is not always true.
const erases the information about whether the original variable was mutable or immutable. This information is hidden even from the compiler.

A consequence of this fact is that const parameters cannot be passed as arguments to functions that take immutable parameters. For example, foo() below cannot pass its const parameter to bar():

Press + to interact
/* NOTE: This program is expected to fail compilation. */
void main() {
/* The original variable is immutable */
immutable int[] slice = [ 10, 20, 30, 40 ];
foo(slice);
}
/* A function that takes its parameter as const, in order to
* be more useful. */
void foo(const int[] slice) {
bar(slice); // ← compilation ERROR
}
/* A function that takes its parameter as immutable, for a
* plausible reason. */
void bar(immutable int[] slice) {
// ...
}

bar() ...