immutabilityreadonlyballerinaisolation

Invalid access of mutable storage in an isolated Ballerina function despite using final keyword in ballerina


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

  • The difference between final and readonly is as follows.

    The final keyword allows you to mandate that the variable cannot be re-assigned.

    final byte[] sampleArray = [1,2,3,4];
    sampleArray = [5,6,7,8]; // Cannot re-assign
    sampleArray[1] = 2; // Can mutate
    

    However, if you make your array type readonly & byte[], it is immutable.

    readonly & byte[] sampleArray = [1,2,3,4];
    sampleArray = [5,6,7,8]; // Can re-assign
    sampleArray[1] = 2; // Cannot mutate
    

    If you define the variable both final and readonly type, it is not re-assignable and immutable, therefore concurrency-safe. Hence, we don't need locks to access the variable within an isolated function.