阅读 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/