Found some evidence here that enum was supported in Ballerina在某一点,但it seems to have been removed。有谁知道推荐/支持/惯用的方式来处理芭蕾舞女演员中的枚举值?
答案 0 :(得分:3)
是的,我们不久前已从语言中删除了枚举类型。现在,您可以使用常量和联合类型来通用地定义枚举值。
// 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;
同样,您可以定义一个新的类型定义,其中仅包含一些这样的值。这里0
表示具有值0
的单例类型,而1
表示具有值1
的另一个单例类型。单例类型是其值集中只有一个值的类型。
type ZeroOrOne 0 | 1;
有了这样的理解,我们可以如下重写我们的Weekday
类型。
type Weekday 0 | 1 | 2 | 3 | 4 | 5| 6;
定义诸如const SUN = 0
之类的编译时常量时,变量SUN
的类型不是int
,而是值为0
的单例类型。