Search code examples
grailsgroovyenums

Correct way to use Enums in Groovy and Grails


I want to create a number of global enums that are for use throughout my entire application.

I created a groovy file called enums which looks something like this:

class Enums {
    enum GameType{
        Game1,
        Game2,
        Game3
        Game4
        Game5
    }

    enum Enum2{
        Type1,
        Type2,
        Type3
    }

}

The first enum seems to work fine, but when I try to use the second one I get an 'unable to resolve class' error. What is the correct way to work with Enums in Grails?


Solution

  • Each enumeration should be in it's own class located under in src/groovy. I would also suggest using a package for them. Your example should be

    src/groovy/my/example/GameType.groovy:

    package my.example
    enum GameType{
      Game1,
      Game2,
      Game3,
      Game4,
      Game5
    }
    

    src/groovy/my/example/Enum2.groovy:

    package my.example
    enum Enum2 {
      Type1,
      Type2,
      Type3
    }