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 ?
Yes, the "?:" operator will return the value to the left, if it is not null. Else, return the value to the right. "Yes, the "?:" operator will return the value to the left, if it is not null." - That is incorrect.
String specialCharRegex = "[\\W|_]"; ... term = term. replaceAll(specialCharRegex, "\\\\\$0"); ... String specialCharRegex = "[\\W|_]"; ...
Groovy - Concatenation of Strings The concatenation of strings can be done by the simple '+' operator. Parameters − The parameters will be 2 strings as the left and right operand for the + operator.
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:
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. /
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!
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
There's also slashy strings /hello $a/
which are templated
And dollar slashy Strings $/hello $a/$
which are multi-line and templated
They're all documented quite well in the documentation
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With