Ballerina 中的 final 和 const 有什么区别?
What is the difference between final and const in 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有什么区别?
答案隐藏在另一个例子中,在列表的后面:https://ballerina.io/learn/by-example/constants.html
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 上的示例时,我偶然发现了此处的示例 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有什么区别?
答案隐藏在另一个例子中,在列表的后面:https://ballerina.io/learn/by-example/constants.html
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
可用于其他编译时结构。