Ben Ripkens

back to blog index

Quick post: How to use Groovy multi-line GStrings for single-line messages

Need to put a long string into your source code but don’t want to violate the 80 character line limit (yes, I prefer it)? You can do it by adding a new method to java.lang.String as the following listing shows.

def toSingleLinePattern = ~/\s{2,}/
String.metaClass.toSingleLine = {
    (delegate =~ toSingleLinePattern).replaceAll(' ')
}

println """This could be an error message which is very long
    and which would need to span several lines if you have a line
    length limitation of 80 characters or similar.""".toSingleLine()
That's me, Ben.
Hey, I am Ben Ripkens (bripkens) and this is my blog. I live in Düsseldorf (Germany) and I am employed by the codecentric AG as a Software Engineer. Web application frontends are my main area of expertise, but you may also find some other interesting articles on this blog.