E4142

E4142#

This 'const' declaration is not constant.

In MoonBit, you can use const to declare a constant value. Only literal value of immutable primitive types can be assigned to const.

  • These are constant values: 1, "String", 1.0, true, false, etc.

  • These are not constant values: [1, 2, 3], 1 + 1, fn() { 1 }, etc.

Erroneous example#

pub const A : Int = [1, 2, 3].length() // Error: This 'const' declaration is not constant.

Suggestion#

As it is not possible to run the computation at compile time and assign the result to a const, you can use a let declaration to calculate these result at initialization time instead.

pub let a : Int = [1, 2, 3].length() // This will be computed at initialization time.

If you can compute the value yourself by using, say a calculator, you can simply assign the result to the const.

pub const A : Int = 3 // This is a constant value.