ballerinaisolation

Invoking isolated langlib function within isolated function in Ballerina


import ballerina/io;

type Person readonly & record {|
    string name;
    int age;
|};

public isolated function main() returns error? {
    string[] fields = ["name", "age", "address"];
    Person p = {name: "John", age: 30};

    string[] validFields = fields.filter(fieldName => p.keys().indexOf(fieldName) > -1);
    io:println(validFields);
}

Please consider the above code. Here main function is isolated and within that we call another isolated function filter. But we get an error as shown below.

incompatible types: expected an 'isolated' function

The error comes when we access the p inside the filter function.

How to fix this issue?


Solution

  • In this example filter in an isolated function. When a langlib function that accepts a function argument, it usually has the @isolatedParam annotation, which will require the argument function to be isolated if the langlib function is called in an isolated function. This is to ensure that the isolated function continues to call only functions that are isolated.

    Please check the source. https://github.com/ballerina-platform/ballerina-lang/blob/v2201.5.0/langlib/lang.array/src/main/ballerina/array.bal#L130

    p is a captured variable within the argument function, it's defined outside the function and is neither a final variable nor it is guaranteed to be an immutable value. So p cannot be accessed within the isolated function. That is the reason for the error. If p is final and immutable, p can be accessed within the isolated function.

    final readonly & Person p = {name: "John", age: 30};