Enums are the next problem in Java to CoffeeScript conversion. Let's see, how to write a enum in CoffeeScript.
The first way is quite simple and obvious. If the only thing that we want from enum is providing a set of values that we can compare with each other, we can write it as follows:
Seasons = {WINTER : 0, SPRING : 1, SUMMER : 2, AUTUMN : 3}
Simple, isn't it? We just declare a new
Object
, that contains several properties - our enum constants. Now we can use it:
commentSeason = (season) ->
switch season
when Seasons.WINTER
console.log "The coldest season"
when Seasons.SUMMER
console.log "The hottest season"
else
console.log "The rainy season"
commentSeason Seasons.WINTER
commentSeason Seasons.SUMMER
commentSeason Seasons.SPRING
console.log "Are spring and autumn the same? %s",
if (Seasons.SPRING == Seasons.AUTUMN) then "Yes" else "No"
The output is:
The coldest season
The hottest season
The rainy season
Are spring and autumn the same? No
Well, this variant is incredibly simple and will be enough for most of the situations when you decide to use enum in your code. But what should you do if you want to use some of these Java enum features like getting constant name, or finding constant by name, or using constructors for creating constants and adding methods to them? My solution is below.