I’m trying to use a module-level array inside an isolated function in Ballerina. To ensure immutability, I used the final keyword when declaring the array. However, I’m encountering an error indicating "invalid access of mutable storage in an ‘isolated’ function (BCE3943)" when attempting to access the array within the isolated function.
I declared a final array as follows:
final byte[] sampleArray = [1,2,3,4];
I then tried to access this array within an isolated function:
isolated function accessFinalArray() returns error? {
var copy = sampleArray;
}
I expected that using the final keyword would make the array immutable, allowing it to be accessed within an isolated function without issues. However, the code results in the error mentioned above. I’m unsure why this error occurs despite marking the array as final. How can I correctly use a module-level array in an isolated function while ensuring immutability?
>Solution :
You can make a byte array immutable in Ballerina by defining it with the readonly type modifier. Here’s an example:
final readonly & byte[] sampleArray = [1, 2, 3, 4];
For more details on how immutability is enforced with the readonly type, you can check out https://ballerina.io/learn/by-example/readonly-type.