What's the difference of strings within single or double quotes in groovy?

StringGroovy

String Problem Overview


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

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

String Solutions


Solution 1 - String

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.

Solution 2 - String

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

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
QuestionFreewindView Question on Stackoverflow
Solution 1 - Stringtim_yatesView Answer on Stackoverflow
Solution 2 - StringjulxView Answer on Stackoverflow