Polyglot Series in Javascript, Dart, Ruby, Python,Go: Enum
Arthur Christoph
Posted on May 24, 2020
Playground path: collection/enum
Enum
Javascript does not have enum type, however Typescript does have enum type. The default value type is numeric, enum type can also be of string type.
Typescript
// numeric enum
enum Color {
Red,
Green,
Blue,
}
// string enum
enum Answer {
No = '1',
Yes = '2',
}
// printing its value: 0
console.log(Color.Red);
console.log(Color.Red.valueOf());
// printing its name: 'Red'
console.log(Color[Color.Red]);
// enum is hashable
let m = new Map();
m.set(Color.Red, 1);
console.log(m.get(Color.Red));
Dart
In Dart, the enum type is enum. To get its enum name, unlike Javascript, the default and toString() print its actual name instead of the value but it prints the fullname of it: 'Color.red'. Flutter framework has a method describeEnum that can extract just the 'red' value or you can come up with a regex.
enum Color { red, green, blue }
// Color.red is an enum type, this will print 'Color.red'
print(Color.red);
// Printing its name can be done with toString() as well
print(Color.red.toString());
// enum type has index property starting at 0
print(Color.red.index);
// enum type is hashable
var m = Map();
m[Color.red] = 1;
print(m[Color.red]);
Python
Enum in Python has to be imported from enum package and the values have to declared - not defaulted to numeric value.
The methods are nicely named and predictable: name,value
In addition, the enum is iterable and accessible like Dictionary as well. So, Python has the most complete feature of all other languages.
from enum import Enum
#the enum values must be declared
class Color(Enum):
red = 1
green = 2
blue = 3
print(Color.red)
# enum name and value are printable
print(Color.red.name)
print(Color.red.value)
# it can be enumerated
for c in Color:
print(c)
# like Javascript, it can be accessed like Map
print(Color['red'])
print(Color(1))
Ruby
Ruby does not have enum, we can use module instead, and must be capitalized, e.g: Red instead of red.
module Color
Red = 1
Green = 2
Blue = 4
end
p Color::Red
Go
Like Ruby, Go does not have enum either. One way to simulate this is to make a list of constants with iota value - a sequential integer value
type Color int
const (
Red Color = iota
Green
Blue
)
fmt.Println(Red, Green, Blue)
var d Color = 0
// it will print Red
switch d {
case Red:
fmt.Println("Red")
default:
fmt.Println("Other Color")
}
Posted on May 24, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.