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?
In this example
filterin anisolatedfunction. When a langlib function that accepts a function argument, it usually has the@isolatedParamannotation, which will require the argument function to beisolatedif the langlib function is called in anisolatedfunction. This is to ensure that theisolatedfunction continues to call only functions that areisolated.Please check the source. https://github.com/ballerina-platform/ballerina-lang/blob/v2201.5.0/langlib/lang.array/src/main/ballerina/array.bal#L130
pis 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. Sopcannot be accessed within the isolated function. That is the reason for the error. Ifpis final and immutable,pcan be accessed within the isolated function.