Using "$" in Groovy

GrailsGroovy

Grails Problem Overview


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?

Grails Solutions


Solution 1 - Grails

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.

Solution 2 - Grails

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'()

Solution 3 - Grails

$ is not an operator in Groovy. In string substitution it identifies variables within the string - there's no magic there. It's a common format used for inline variables in many template and programming languages.

All special Groovy operators are listed here: http://groovy-lang.org/operators.html

Solution 4 - Grails

Work in side Jenkins File in pipeline enter image description here

#!/usr/bin/env groovy
node{
          stage ('print'){
             def DestPath="D\$\\"
             println("DestPath:${DestPath}")
          }
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionRayView Question on Stackoverflow
Solution 1 - GrailsNicolas ModrzykView Answer on Stackoverflow
Solution 2 - GrailsDónalView Answer on Stackoverflow
Solution 3 - GrailsOverZealousView Answer on Stackoverflow
Solution 4 - GrailsRobert AView Answer on Stackoverflow