groovy中单引号或双引号内的字符串有什么区别? [英] What's the difference of strings within single or double quotes in groovy?

查看:448
本文介绍了groovy中单引号或双引号内的字符串有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  def a =a string
def b ='another'

是否有区别?或者就像javascript让我们在字符串中输入'更容易



双引号是一个模板化的String,它将返回一个GString如果是模板化的,或者是标准的Java String。例如:

  println'hi'.class.name //打印java.lang.String 
printlnhi.class.name //打印java.lang.String

def a ='Freewind'
printlnhi $ a/ / printshi Freewind
printlnhi $ a.class.name //打印org.codehaus.groovy.runtime.GStringImpl

如果您尝试使用单引号字符串进行模板化,那么它不会执行任何操作,因此:

  println'hi $ a'//打印出hi $ a

另外, a href =https://stackoverflow.com/questions/6761498/whats-the-difference-of-strings-within-single-or-双引号在/ groovy / 6761595#6761595>由julkiewicz在他们的答案中给出的链接值得一读(特别是,关于GStrings的部分不是Strings的2/3左右。


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

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

解决方案

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

这篇关于groovy中单引号或双引号内的字符串有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆