arraysloopsballerina

How to iterate over Array or nil ([]?) type in Ballerina?


I have a variable of type Array or nil([]?) and I am trying to iterate over each element.

mysql:Client db = check new (host, user, password, database, port);
stream<Brewery, sql:Error?> rez = db->query(query);
Brewery[]? brewery = check from Brewery brwr in rez select brwr;

Brewery[]? does not look like it can be iterated. What should I change in above code to iterate over each element in Brewery[]? brewery

Additionally, is there a way to take only the top 5 items in the statement, Brewery[]? brewery = check from Brewery brwr in rez select brwr;?


Solution

  • You need to narrow the type of the variable down to an array type before using it as an array. For example, you can use the is check in an if-else statement.

    if brewery is () {
        // Handle the nil scenario.
    } else {
        // The type of `brewery` is narrowed to `Brewery[]` here,
        // so it can be used in a `foreach` statement.
        foreach Brewery item in brewery {
            
        }
    }
    

    As for the second question, you can use the limit clause to limit the number of values.

    Brewery[]? brewery = check from Brewery brwr in rez limit 5 select brwr;
    

    Please refer to the documentation for limit-clause.