133
def a = "a string"
def b = 'another'

Is there any difference? Or just like javascript to let's input ' and " easier in strings?

Freewind
  • 193,756
  • 157
  • 432
  • 708

3 Answers3

196

Single quotes are a standard java String

Double quotes are a templatable String, which will either return a GString if it is templated, or else a standard Java String. For example:

println 'hi'.class.name    // prints java.lang.String
println "hi".class.name    // prints java.lang.String

def a = 'Freewind'
println "hi $a"            // prints "hi Freewind"
println "hi $a".class.name // prints org.codehaus.groovy.runtime.GStringImpl

If you try templating with single quoted strings, it doesn't do anything, so:

println 'hi $a'            // prints "hi $a"

Also, the link given by julx in their answer is worth reading (esp. the part about GStrings not being Strings about 2/3 of the way down.

Ricibob
  • 7,505
  • 5
  • 46
  • 65
tim_yates
  • 167,322
  • 27
  • 342
  • 338
  • 7
    Good point about the GString not being String. This becomes problematic with equals comparisons failing between GString and String even though they contain the same characters. This is something you just got to learn to look out for, particularly when referencing String/GString keys in maps. – Steven Jul 21 '11 at 03:24
22

My understanding is that double-quoted string may contain embedded references to variables and other expressions. For example: "Hello $name", "Hello ${some-expression-here}". In this case a GString will be instantiated instead of a regular String. On the other hand single-quoted strings do not support this syntax and always result in a plain String. More on the topic here:

http://docs.groovy-lang.org/latest/html/documentation/index.html#all-strings

mkobit
  • 43,979
  • 12
  • 156
  • 150
julx
  • 8,694
  • 6
  • 47
  • 86
1

I know this is a very old question, but I wanted to add a caveat.

While it is correct that single (or triple single) quotes prevent interpolation in groovy, if you pass a shell command a single quoted string, the shell will perform parameter substitution, if the variable is an environment variable. Local variables or params will yield a bad substitution.

Wyrmwood
  • 3,340
  • 29
  • 33