[英]What is the difference between final and const in Ballerina?
Reading the examples on Ballerina I stumbled upon the example here https://ballerina.io/learn/by-example/variables.html which has the following code:阅读 Ballerina 上的示例时,我偶然发现了示例https://ballerina.io/learn/by-example/variables.html ,它具有以下代码:
public const int COUNT = 1;
final int status = 1;
where the first line is only described with其中第一行仅描述为
Declare a
public
compile-time constant声明一个
public
编译时常量
and the second is:第二个是:
Declare a final variable.
声明一个最终变量。 The value of the
final
variable is read-only.final
变量的值是只读的。 Once a value is assigned to a final variable, it becomes immutable.一旦将值分配给最终变量,它就变得不可变。 All parameters of a function call are implicitly final.
function 调用的所有参数都是隐式最终的。
But this leads to the question: what is the difference between final and const?但这引出了一个问题:final 和 const 有什么区别?
The answer is hidden in another example, a lot later in the list: Const and final答案隐藏在另一个示例中,在列表后面很多: Const 和 final
The difference between the final variables and constants is that the value of the final variables can be initialized at runtime.
final变量和常量的区别在于final变量的值可以在运行时初始化。 However, constants must be initialized at compile time.
但是,常量必须在编译时初始化。
Which means意思是
function findFoo() returns int {
return 42;
}
public function main() {
// This works
final int foo = findFoo();
}
however:然而:
function findFoo() returns int {
// this is not allowed
return 42;
}
public function main() {
const int foo = findFoo();
}
Previously there was a bug ( https://github.com/ballerina-platform/ballerina-lang/issues/15044 ) in the language implementation that has now been fixed:以前在语言实现中存在一个错误( https://github.com/ballerina-platform/ballerina-lang/issues/15044 ),现已修复:
int foo;
// this previously didn't work, but now does
foo = 32;
That is using final
allows one to set the value from a function (ie, at runtime) where const doesn't.也就是说,使用
final
允许从 const 不允许的 function (即在运行时)设置值。 Currently in both cases one need to set the value where one declares the variable, but in a future version (when the bug is fixed) the definition can be later in the code.目前在这两种情况下都需要设置一个声明变量的值,但在未来的版本中(当错误修复时),定义可以在代码的后面。
On the other hand (thanks to @dhananjaya for pointing that out) const
can be used in other compile time constructs.另一方面(感谢@dhananjaya 指出)
const
可用于其他编译时构造。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.