如何在Ballerina的隔离函数中使用`map`函数

huangapple go评论47阅读模式
英文:

How to use map function inside an isolated function in Ballerina

问题

以下是我的代码。VS Code 插件报错,表示在 map 内部使用的函数不是隔离函数。这有什么问题。

class Node {
    (int|string)[] path;

    隔离函数 init((int|string)[] path) {
        self.path = path;
    }

    隔离函数 getPath() 返回 string[] {
        return self.path.clone().map(n => n is int ? "@" : n);
    }
}
英文:

Following is my code. VS code plugin complains that the function used inside the map is not an isolated function. What is the problem with it.

class Node {
    (int|string)[] path;

    isolated function init((int|string)[] path) {
        self.path = path;
    }

    isolated function getPath() returns string[] {
        return self.path.clone().'map(n => n is int ? "@" : n);
    }

}

答案1

得分: 1

错误似乎是由于参数的类型缩小,推断匿名函数是否为isolated函数时存在错误

作为一种解决方法,您需要明确指定该函数是isolated函数。

class Node {
    (int|string)[] path;

    isolated function init((int|string)[] path) {
        self.path = path;
    }

    isolated function getPath() returns string[] {
        return self.path.map(
            isolated function (int|string n) returns string => n is int ? "@" : n);
    }
}
英文:

The error here seems to be due to a bug in inferring if the (infer) anonymous function is an isolated function when there's type narrowing of a parameter.

As a workaround, you would have to explicitly specify that the function is an isolated function.

class Node {
    (int|string)[] path;

    isolated function init((int|string)[] path) {
        self.path = path;
    }

    isolated function getPath() returns string[] {
        return self.path.map(
            isolated function (int|string n) returns string => n is int ? "@" : n);
    }
}

huangapple
  • 本文由 发表于 2023年3月4日 08:37:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/75632944.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定