我试过if(string? myStr)
了,但这会在编辑器中出现语法错误。如何在 Ballerina 中进行类型检查?
4 回答
您可以为此使用类型保护语句,
例如:
if (myStr is string) {
io:println("This is String");
} else {
io:println("This isn't String");
}
您可以在此处使用类型切换(匹配)语句或匹配语句的表达式版本。这是一个例子。
import ballerina/io;
function main (string... args) {
any a = "some string value";
// If the type of the variable a is string executes the first block, if not the second block.
match a {
string s => { io:println("string type");}
any k => {io:println("any other type");}
}
}
请参阅以下示例以获取更多信息。 https://ballerina.io/learn/by-example/match.html
我确信这可能是一个次优答案(即不涵盖所有方面),但我发现在 Ballerina 1.0(实现语言规范 2019R3)中可以使用type test expression。
我发现的最好的文档是:
- https://ballerina.io/learn/by-example/type-test-expression.html
- https://ballerina.io/learn/by-example/type-guard.html
这是一个使用union和任何类型的 Ballerina 1.0 示例:
import ballerina/io;
public function main() {
// union type
int|error a = 0;
io:print("typeof a: ");
io:println(typeof a); // typeof expression
// type test expression
if (a is int) {
io:println("a is int");
} else {
io:println("a is error");
}
// any type
any b = "string";
io:print("typeof b: ");
io:println(typeof b); // typeof expression
// type test expression
if (b is int) {
io:println("b is int");
} else if (b is string) {
io:println("b is string");
} else {
io:println("b is something else");
}
}
运行时打印:
$ ballerina run test.bal
typeof a: typedesc int
a is int
typeof b: typedesc string
b is string
检查类型的用例是什么?
根据规范类型和值是根据它们的结构自动确定的
Ballerina 的类型系统比传统的静态类型语言灵活得多。首先,它是结构性的:不需要程序明确说明哪些类型相互兼容,类型和值的兼容性是根据它们的结构自动确定的;这在组合来自多个独立设计系统的数据的集成场景中特别有用。其次,它提供联合类型:两种或多种类型的选择。第三,它提供了开放记录:除了在其类型定义中明确命名的字段之外,还可以包含字段的记录。这种灵活性使其还可以用作分布式应用程序中交换的数据的模式。Ballerina 的数据类型被设计为与 JSON 一起工作得特别好;任何 JSON 值都有一个直接的,自然表现作为芭蕾舞女演员的价值。Ballerina 还提供对 XML 和关系数据的支持。