Found some evidence here that enum was supported in Ballerina at one point, but it seems to have been removed. Is anyone aware of a recommended/supported/idiomatic way to deal with enumerated values in Ballerina?
1 Answers
Yes, we had removed the enum type from the language a while ago. Now you can generically define enumerated values using constants and the union type.
// 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;
}
Let me explain how this works according to the language specification. Consider the following type definition. You can assign possible integer values as well as boolean values (true
or false
) to a variable of type IntOrBoolean
.
type IntOrBoolean int | boolean;
IntOrBoolean v1 = 1;
IntOrBoolean v2 = false;
Likewise, you can define a new type definition which contains only a few values such as this. Here 0
denotes a singleton type which has value 0
and 1
denotes another singleton type which has the value 1
. Singleton type is a type which has only one value in its value set.
type ZeroOrOne 0 | 1;
With this understanding, we can rewrite our Weekday
type as follows.
type Weekday 0 | 1 | 2 | 3 | 4 | 5| 6;
When you define a compile-time constant such as const SUN = 0
, the type of the variable SUN
is not int
, but a singleton type with the value 0
.

- 1,545
- 8
- 12
-
Thanks. It's a bit awkward, but will have to do. – WillD Jun 11 '19 at 16:59
-
I understand. Ballerina doesn't have a straightforward way to define enumerated values. – Sameera Jayasoma Jun 11 '19 at 18:26