string groovy中单引号或双引号内的字符串有什么区别?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6761498/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 01:10:10  来源:igfitidea点击:

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

stringgroovy

提问by Freewind

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

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

有什么区别吗?或者就像 javascript 让我们在字符串中输入'"更容易?

回答by tim_yates

Single quotes are a standard java String

单引号是标准的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:

双引号是一个可模板化的字符串,如果它是模板化的,它将返回一个 GString,否则将返回一个标准的 Java 字符串。例如:

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 julkiewicz in their answeris worth reading (esp. the part about GStrings not being Strings about 2/3 of the way down.

此外,julkiewicz 在他们的回答中给出链接值得一读(特别是关于 GStrings 的部分不是字符串大约 2/3。

回答by julx

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 GStringwill 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:

我的理解是双引号字符串可能包含对变量和其他表达式的嵌入引用。例如:"Hello $name""Hello ${some-expression-here}"。在这种情况下, aGString将被实例化而不是常规String。另一方面,单引号字符串不支持这种语法,并且总是导致一个普通的String. 更多关于这里的主题:

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

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