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.

错误示例#

const A : Int = 1 + 1 // Error: This 'const' declaration is not constant.

建议#

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.

let a : Int = 1 + 1 // These 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.

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