Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using "$" in Groovy

Tags:

grails

groovy

I see { } are used for closures, and then I believe when a $ is put in front of braces, it is simply doing a variable substitution within a string. I can't find the documentation on how the $ works in the reference ... hard to search on it unfortunately, and the Groovy String documentation is lacking in introducing this. Can you please point me to the documentation and/or explain the "$" operator in Groovy -- how all it can be used? Does Grails extend it at all beyond Groovy?

like image 908
Ray Avatar asked Aug 03 '11 01:08

Ray


People also ask

How do you use special characters in Groovy?

String specialCharRegex = "[\\W|_]"; ... term = term. replaceAll(specialCharRegex, "\\\\\$0"); ... String specialCharRegex = "[\\W|_]"; ...

What does [:] mean in Groovy?

[:] creates an empty Map. The colon is there to distinguish it from [] , which creates an empty List. This groovy code: def foo = [:]

How do I use variables in Groovy?

Variables in Groovy can be defined in two ways − using the native syntax for the data type or the next is by using the def keyword. For variable definitions it is mandatory to either provide a type name explicitly or to use "def" in replacement. This is required by the Groovy parser.

How do you use and operator in Groovy?

Logical operators Groovy offers three logical operators for boolean expressions: && : logical "and" || : logical "or" ! : logical "not"


2 Answers

In a GString (groovy string), any valid Groovy expression can be enclosed in the ${...} including method calls etc.

This is detailed in the following page.

like image 89
Nicolas Modrzyk Avatar answered Oct 03 '22 00:10

Nicolas Modrzyk


Grails does not extend the usage of $ beyond Groovy. Here are two practical usages of $

String Interpolation

Within a GString you can use $ without {} to evaluate a property path, e.g.

def date = new Date() println "The time is $date.time" 

If you want to evaluate an expression which is more complex than a property path, you must use ${}, e.g.

println "The time is ${new Date().getTime()}" 

Dynamic Code Execution

Dynamically accessing a property

def prop = "time" new Date()."$prop" 

Dynamically invoking a method

def prop = "toString" new Date()."$prop"() 

As pointed out in the comments this is really just a special case of string interpolation, because the following is also valid

new Date().'toString'() 
like image 34
Dónal Avatar answered Oct 03 '22 02:10

Dónal