Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Groovy String variable replacement

Tags:

string

groovy

When looking at examples of variable substitution in GStrings, I have noticed two difference syntaxes. This can be seen here: Groovy Templates

This has the example:

def text = 'Dear "$firstname $lastname",\nSo nice to meet you in <% print city %>.\nSee you in ${month},\n${signed}'

It looks like ${variable} is used more commonly when you have an expression, but $variable is used when you just have a single variable, but even here they mix it with $firstname and ${month}. Is there a reason to do it one way or another when you have a single variable and not an expression, or does it not matter?

like image 831
user1712917 Avatar asked Jun 14 '13 16:06

user1712917


1 Answers

It doesn't matter...

As you say, if you have an expression like "${name.toUpperCase()}", "${number}th" or "${list[0]}", then it has to be inside braces, but both "${name}" and "$name" are the same.

Indeed, so long as it's simple property access you can omit the braces, ie: "Hello $person.username"

It could be said that adding the braces can make your string templates easier to read, but that's a personal preference thing.

like image 184
tim_yates Avatar answered Oct 11 '22 01:10

tim_yates