Search code examples
arrayssizedynamic-arraysballerina

How to create an array with dynamic size at runtime in Ballerina?


It seems currently it only allows compile-time constants for the array size in the array type descriptor. E.g.

const ARR_SIZE = 2;

public function main() {
    int[] arr1 = []; // okay
    int[2] arr2 = []; // okay
    int[ARR_SIZE] arr3 = []; // okay
    int array_size = 4;
    // int[array_size] arr4 = []; // not okay, gives compilation error: "invalid reference expression 'array_size' as array size: expected a constant reference expression"
}

What is the easiest way to create an array whose size is not a compile time constant?


Solution

  • As seen in the question, the array type descriptor only allows compile-time constants for the array size. Hence, there is no way to create a fixed length array whose size is only known at runtime.

    What you can do is creating a variable length array and changing its length at runtime. If the array type has a filler value, the easiest and the fastest way to expand an array to a particular length at runtime is to use the array member assignment statement or you can use the array:setLength function.

    import ballerina/io;
    import ballerina/lang.array;
    
    public function main() {
        int array_size = 4;
        int[] arr = [];
        arr[array_size - 1] = 1;
        io:println(arr); // [0,0,0,1]
    
        array:setLength(arr, array_size + 3);
        io:println(arr); // [0,0,0,1,0,0,0]
    
        arr.setLength(array_size - 1);
        io:println(arr); // [0,0,0]
    }
    

    Otherwise we have to push members to the array until we get the required size.

    import ballerina/io;
    
    public function main() {
        int array_size = 4;
        string:Char[] arr = [];
        // arr[array_size - 1] = "0"; // error: "array of length 0 cannot be expanded into array of length 4 without filler values"
    
        foreach int i in 0..<array_size {
            arr.push("0");
        }
        io:println(arr); // ["0","0","0","0"]
    }