Correct way to use Enums in Groovy and Grails
26,270
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
}
Related videos on Youtube
Author by
user1636130
Updated on October 15, 2020Comments
-
user1636130 over 3 years
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?
-
Burt Beckwith about 10 yearsYou mean
/src/groovy
notgrails-app/src/groovy
right? -
Joshua Moore about 10 yearsIndeed I did. Fixed that. Thanks for the spot check. Guess my brain checked out for a bit.
-
Jay Edwards about 7 yearsIn Grails, I tend to use Enums as properties within services; say, if I have an enduring business need to use
enum foobar { FOO, BAR }
on methods explicitly within FooBarService. However, that is assuming I only want to use that enum within that service (or it is used elsewhere but relates to some common theme of that service - e.g. I'm performing some kind of action with a relatedFoo
andBar
domain Class within a different service). I haven't really found much use for enum beyond that within Grails. Ergo, this is in addendum to the above rather than an answer in itself.