operators – vs vs in Groovy .When to Use What?

operators – vs vs in Groovy .When to Use What?

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

So, whats 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 dont 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 dont 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!

Single quotes are for basic Strings

Double quotes are for templated Strings ie:

def a = tim
assert Hi $a == Hi tim

Triple single quotes are for multi-line basic Strings

Triple double quotes are for multi-line templated strings

Theres also slashy strings /hello $a/ which are templated

And dollar slashy Strings $/hello $a/$ which are multi-line and templated

Theyre all documented quite well in the documentation

operators – vs vs in Groovy .When to Use What?

Leave a Reply

Your email address will not be published. Required fields are marked *