Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
524 views
in Technique[技术] by (71.8m points)

operators - ' vs " " vs ' ' ' in Groovy .When to Use What?

I am getting really confused in Groovy. When to use what for Strings in Groovy ?

1) Single Quotes - ' '
2) Double Quotes - " "
3) Triple Quotes - '''

My code:

 println("Tilak Rox")
 println('Tilak Rox')
 println('''Tilak Rox''')

All tend to produce same results. When to Use What ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I would confuse you even more, saying, that you can also use slash /, dolar-slash $/ and triple-double quotes """ with same result. =)

So, what's the difference:

  1. Single vs Double quote: Most important difference. Single-quoted is ordinary Java-like string. Double-quoted is a GString, and it allows string-interpolation. I.e. you can have expressions embedded in it: println("${40 + 5}") prints 45, while println('${ 40 + 5}') will produce ${ 40 + 5}. This expression can be pretty complex, can reference variables or call methods.
  2. Triple quote and triple double-quote is the way to make string multiline. You can open it on one line in your code, copy-paste big piece of xml, poem or sql expression in it and don't bother yourself with string concatenation.
  3. Slashy / and dollar-slashy $/ strings are here to help with regular expressions. They have special escape rules for '' and '/' respectfully.

As @tim pointed, there is a good official documentation for that, explaining small differences in escaping rules and containing examples as well.

Most probably you don't need to use multiline/slashy strings very often, as you use them in a very particular scenarios. But when you do they make a huge difference in readability of your code!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...