ballerina - Ballerina 中的final 和const 有什么区别?

标签 ballerina

阅读 Ballerina 上的示例时,我偶然发现了这里的示例 https://ballerina.io/learn/by-example/variables.html其中有以下代码:

public const int COUNT = 1;

final int status = 1;

其中第一行仅用

描述

Declare a public compile-time constant

第二个是:

Declare a final variable. The value of the final variable is read-only. Once a value is assigned to a final variable, it becomes immutable. All parameters of a function call are implicitly final.

但这引出了一个问题:final 和 const 有什么区别?

最佳答案

答案隐藏在列表后面的另一个示例中:Const and final

The difference between the final variables and constants is that the value of the final variables can be initialized at runtime. However, constants must be initialized at compile time.

这意味着

function findFoo() returns int {
    return 42;
}

public function main() {
    // This works
    final int foo = findFoo();
}

但是:

function findFoo() returns int {
    // this is not allowed
    return 42;
}

public function main() {
    const int foo = findFoo();
}

之前语言实现中存在一个错误 ( https://github.com/ballerina-platform/ballerina-lang/issues/15044 ),现已修复:

int foo;
// this previously didn't work, but now does
foo = 32;

使用final允许人们从函数中设置值(即在运行时),而const则不能。目前,在这两种情况下,都需要在声明变量的地方设置值,但在未来版本中(当错误修复时)定义可以稍后在代码中进行。

另一方面(感谢 @dhananjaya 指出)const 可以在其他编译时构造中使用。

关于ballerina - Ballerina 中的final 和const 有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58078367/

相关文章:

elasticsearch - Ballerina 集成器和 Elasticsearch

json - Ballerina,使用来自 REST-API 的 Json 响应

transactions - 在 Ballerina 中获取没有回调的交易状态

ballerina - 我可以获得联合类型变量的实际类型吗?

wso2 - 芭蕾舞女 Actor 准备好生产了吗?

wso2 - 尝试将外部 jar 导入 ballerina 模块时出错

types - 当使用剩余字段定义记录时,类型缩小不起作用

kubernetes - 芭蕾舞女 Actor “undefined package ”与Visual Code中的kubernetes

ballerina - 如何在 Ballerina 中创建列表列表?

aws-lambda - 将 Ballerina 部署为 AWS Lambda 函数