【问题标题】:What is the idiomatic way to create and use Enumerations in Ballerina?在 Ballerina 中创建和使用枚举的惯用方式是什么?
【发布时间】:2019-06-10 14:22:05
【问题描述】:

Found some evidence here that enum was supported in Ballerina 在某一时刻,但it seems to have been removed。有人知道在 Ballerina 中处理枚举值的推荐/支持/惯用方式吗?

【问题讨论】:

    标签: ballerina ballerina-composer


    【解决方案1】:

    是的,我们刚刚从语言中删除了枚举类型。现在您可以使用常量和联合类型一般地定义枚举值。

    // Following declarations declare a set of compile-time constants. 
    // I used the int value for this example. You could even do const SUN = "sun". 
    const SUN = 0;
    const MON = 1;
    const TUE = 2;
    const WED = 3;
    const THU = 4;
    const FRI = 5;
    const SAT = 6;
    
    // This defines a new type called "Weekday"
    type Weekday SUN | MON | TUE | WED | THU | FRI | SAT;
    
    function play() {
        Weekday wd1 = WED;
        Weekday wd2 = 6;
    
        // This is a compile-time error, since the possible values 
        //  which are compatible with the type "Weekday" type are 0, 1, 2, 3, 4, 5, and 6
        Weekday wd3 = 8;
    }
    

    让我根据语言规范解释一下这是如何工作的。考虑以下类型定义。您可以将可能的整数值和布尔值(true 或 false)分配给 IntOrBoolean 类型的变量。

    type IntOrBoolean int | boolean;
    IntOrBoolean v1 = 1;
    IntOrBoolean v2 = false;
    

    同样,您可以定义一个新的类型定义,它只包含几个值,例如 this。这里0 表示一个单例类型,其值为0,1 表示另一个单例类型,其值为1。单例类型是一种在其值集中只有一个值的类型。

    type ZeroOrOne 0 | 1;
    

    有了这个理解,我们可以重写我们的Weekday类型如下。

    type Weekday 0 | 1 | 2 | 3 | 4 | 5| 6;
    

    当你定义一个编译时常量比如const SUN = 0时,变量SUN的类型不是int,而是一个值为0的单例类型。

    【讨论】:

    • 谢谢。这有点尴尬,但必须这样做。
    • 我明白了。 Ballerina 没有直接定义枚举值的方法。
    猜你喜欢
    • 2013-01-03
    • 1970-01-01
    • 1970-01-01
    • 2019-03-27
    • 1970-01-01
    • 1970-01-01
    • 2021-04-17
    • 1970-01-01
    相关资源
    最近更新 更多