ballerinaballerina-swan-lake

Getting "incompatible types: expected an 'isolated' function" when trying to filter records in ballerina


I am trying to filter User records in Ballerina. My code is similar to this.

type User record {|
    string id;
    string name;
    int age;
|};

int votingAge = 18;

public isolated function someFunc() returns error? {
    User[] users = [
        {id: "1", name: "John", age: 13},
        {id: "2", name: "Doe", age: 23},
        {id: "3", name: "Adam", age: 19}
    ];
    
    User[] eligibleVoters = users.filter(user => user.age >= votingAge);
}

Here I am getting incompatible types: expected an 'isolated' function error for the following argument user => user.age >= votingAge. How can I fix it?


Solution

  • Notice you are calling the filter() langlib function inside an 'isolated' function.

    If you check the go-to definition of the langlib function (https://github.com/ballerina-platform/ballerina-lang/blob/196825363e81a17f4f71c837bb010046edb5cad4/langlib/lang.array/src/main/ballerina/array.bal#L130), take note of the @isolatedParam annotation. This annotation mandates that the provided argument function must also be marked as isolated if the langlib function is called within an isolated context.

    What you are doing is equivalent to,

    User[] eligibleVoters = users.filter(isolated function(User user) returns boolean {
            return user.age >= votingAge;
        });
    

    Here you are trying to access a mutable value votingAge inside an 'isolated' function. Therefore, you need to make it immutable.

    Making it, final or a constant will fix the issue. i.e. final int votingAge = 18; or const int votingAge = 18; would fix the issue.