In my last blog post I used a Groovy feature to make anonymous inner classes work to illustrate dynamic types using Groovy Maps that I didn’t mention in my first blog post on the topic: the “as” keyword. This keyword let’s you specify a particular type for a dynamic type. This is commonly used when you want to override the default implementation Groovy provides, such as:
The default would have been a List type, but the use of the “as Set” statement lets me override the default. The same principle can be applied to override a Groovy Map’s type. We can implement interfaces using the dynamic nature of Groovy Maps and then use the “as” keyword to override the type from Map to whatever it is we’re implementing.
We see this in the example from my last blog post. The Runnable interface has one method:
1 2 3 |
So I can implement this using Groovy Maps and closures like this:
1 2 3 4 5 6 7 8 9 10 | def r = [run: { try { while (true) { sleep(1000) println '.' } } catch (InterruptedException ex) { // do nothing } }] as Runnable |
The Groovy compiler will let you know at compile time if you missed something in the implementation. And this lets you do some dynamic casting that Groovy would not otherwise allow (due to Java conventions kept in the language).
Another use of the as keyword is to create an alias for an import statement:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | import org.springframework.security.context.SecurityContextHolder as SCH if (!session.personUsername) { def principal = SCH?.context?.authentication?.principal try { session.personUsername = principal.username.toLowerCase() } catch (MissingPropertyException e) { log.debug "There was a problem getting the " + "username property off the principal " + "object; going to redirect the request " + "to the forbidden controller" redirect(controller: 'forbidden', action: 'index', params: [reason: "noUsernameOnPrincipal"]) return true } } |
This might be useful to create a class level singleton object that you can use throughout your class implementation, without having to scope out explicit memory space for it. This might or might not be useful, depending on your circumstance, but it’s another use of the “as” keyword that is good to be aware of.
So there you go. Groovy is fun! Go have fun. Go.
Related posts: