The best IDE to use when developing Groovy code is IntelliJ IDEA. The Groovy plugin has some nice intentions for us that we can use to optimise and refactor our code. We will look at some of the intentions that deal with String values in this blog post. The intentions shown here work in the free Community Edition as well in the paid Ultimate Edition. To see the possible intentions in IDEA we must select the Show Intentions Action. We need to check our shortcut keys to see the assigned shortcut. On my Mac it is for example Alt+Enter. Alternatively we can press the Shift key twice and type in Show intentions. IDEA will show the action with the shortcut key for us.

Suppose we have assigned a String value to a variable in our code. We used the double quoted syntax to do so, like in Java. But we want to change it to a single quoted String value, so to make it explicit the value cannot be a GString implementation. In the following screenshot we see our variable s with a value. We use our shortcut key to open the suggested intentions. We type convert to shorten the list with only conversion options. We see that we can change our String value to dollar slashy, regular expression, multiline or plain String syntax:

When we select Convert to String IntelliJ IDEA changed our value assignment:

We can also apply the conversion the other way around:

Another useful intention, especially when we copy-past some Java code in our Groovy source files, is to convert a String concatenation with the + operator to a GString value. We can select one of the elements of the concatenation and open the Show Intentions Action. Now we see the option Convert to GString:

When we select the option IDEA will turn the statement into a GString with the variable value replaced as an expression:

Also when we already have a GString value in our code we can remove unnecessary braces. In Groovy we can leave out the curly braces for dotted expression or the expression is a single value. We select the option Remove unnecessary braces in GString from the intentions to make this work:

The result is that the braces are removed:

Finally we take a look at the intention to turn a String value with end of line characters in it to a multiline String value:

If we have selected the option Convert to Multiline IDEA turns our original String value to a multiline String value:

Written with Groovy 2.4.4 and IntelliJ IDEA CE 14.1.4

Original article

shadow-left