如何正确比较 Ballerina 中两个变量的类型并确保它们具有相同的类型?

Nuv*_*ana 4 type-equivalence ballerina

我正在与 Ballerina 合作并尝试比较两个变量的类型以确保它们具有相同的类型。代码片段如下所示:

typedesc type1 = typeof input1;
typedesc type2 = typeof input2;  
if type1 == type2 {
   //...
}
Run Code Online (Sandbox Code Playgroud)

类型检查运算==符无法按预期工作。我可以使用type1.toString() == type2.toString(),但它不适用于联合类型和不可变记录。

Nuv*_*ana 5

typedesc可以使用精确(引用)相等运算符 ( ===/ ) 检查相等性!==,如下所示。但是,这种方法和toString()方法不适用于不可变的值。

import ballerina/io;

type Foo record {|
    int a;
|};

type Bar record {|
    int a;
|};

public function main() {
    Foo foo1 = {a: 1};
    Foo foo2 = {a: 1};
    Bar bar = {a: 1};
    io:println(typeof foo1 === typeof foo2); // true  
    io:println(typeof foo1 === typeof bar); // false
}
Run Code Online (Sandbox Code Playgroud)

此外,可以使用运算符单独检查变量的类型is。作为解决方法,可以使用以下方法来比较类型。但是,如果有两个相似的不可变类型变量(简单类型除外)具有不同的字段值,则类型可能不相等。

import ballerina/io;

type Foo record {|
    int a;
|};

type Bar record {|
    int a;
|};

function getType(any value) returns string|error {
    if value is () {
        return "nil";
    } else if value is int {
        return "int";
    } else if value is float {
        return "float";
    } else if value is decimal {
        return "decimal";
    } else if value is boolean {
        return "boolean";
    } else if value is string {
        return "string";
    } else {
        var result = typeof value;
        if (result is typedesc) {
            string typeString = result.toString();
            return typeString.startsWith("typedesc ") ? typeString.substring(9) : typeString;
        } else {
            return result;
        }
    }
}

public function main() returns error? {
    Foo & readonly foo1 = {a: 1};
    Foo & readonly foo2 = {a: 1};
    Bar bar = {a: 1};
    io:println(check getType(foo1) == check getType(foo2)); // true  
    io:println(check getType(foo1) == check getType(bar)); // false
}
Run Code Online (Sandbox Code Playgroud)