【问题标题】:What is the difference between final and const in Ballerina?Ballerina 中的 final 和 const 有什么区别?
【发布时间】:2020-01-24 11:08:00
【问题描述】:

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

public const int COUNT = 1;

final int status = 1;

第一行仅用

描述

声明一个public 编译时常量

第二个是:

声明一个最终变量。 final 变量的值是只读的。一旦将值分配给最终变量,它就变得不可变。函数调用的所有参数都是隐式最终参数。

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

【问题讨论】:

    标签: ballerina


    【解决方案1】:

    答案隐藏在另一个示例中,在列表后面很多:https://ballerina.io/learn/by-example/constants.html

    final变量和常量的区别在于final变量的值可以在运行时初始化。但是,常量必须在编译时初始化。

    这意味着

    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 可用于其他编译时构造。

    【讨论】:

    • 添加到那个 'const' 可以在其他编译时构造中使用,例如类型 const A = 1;常量 B = 2; AorB A 型 | B;
    猜你喜欢
    • 2013-10-28
    • 2015-05-11
    • 2018-10-30
    • 1970-01-01
    • 2015-05-26
    • 2013-07-12
    • 2010-10-27
    相关资源
    最近更新 更多