2

In groovy what does backslash means at the end of line? Specifically what is the sense in the next code from kickstart grails plugin?:

dateFormat = messageSource.getMessage("default.date.format",null,'mm/dd/yyyy',LocaleContextHolder.locale )\
            .replace('z', '').replace('Z', '')\
            .replace('h', '').replace('H', '')\
            .replace('k', '').replace('K', '')\
            .replace('w', '').replace('W', '')\
            .replace('s', '').replace('S', '')\
            .replace('m', '').replace('a', '').replace('D', '').replace('E', '').replace('F', '').replace('G', '').replace(':', '')\
            .replace('MMM', 'MM').replace('ddd', 'dd')\
            .trim()\
            .toLowerCase()
Opal
  • 81,889
  • 28
  • 189
  • 210
iberck
  • 2,372
  • 5
  • 31
  • 41

1 Answers1

2

Since Groovy doesn't use semicolons to indicate line breaks, the backslash character here indicates that the following line is a continuation of the current one. This way any person or compiler will know that

.toLowerCase()

isn't its own statement because the previous line ends in a backslash:

.trim()\
Ari Bustamante
  • 84
  • 2
  • 11
  • 1
    Rubbish. The parser will work anyway. The backslashes there are a waste of characters – tim_yates Oct 14 '15 at 06:22
  • The parser will work (thanks for the "rubbish") in this case, and in nearly all, but it can be used to improve readability. I didn't find much documentation for this feature, but here's an example: https://leanpub.com/groovytutorial/read – Ari Bustamante Oct 14 '15 at 06:30
  • For one more reference (and defense against the downvote), I'll also point out that when Guillaume Laforge responded in this very old nabble thread, he said neither "rubbish" nor that backslashes "have no meaning at all." http://groovy.329449.n5.nabble.com/Why-elvis-instead-of-tp350097p350155.html – Ari Bustamante Oct 14 '15 at 06:56
  • 1
    They only have use in this situation. http://stackoverflow.com/questions/5079797/whats-wrong-with-groovy-multi-line-string/5079914#5079914 for method calls as above, you don't need them. Apologies if the "rubbish" was a bit harsh :-( – tim_yates Oct 14 '15 at 07:02
  • Such backslash is good understood in C/C++ world, especially with mutiline #define – Jacek Cz Oct 14 '15 at 07:22
  • I came here after trying to split a line with array concat `<<` operators into multiple lines and finding that it became a syntax error unless I ended the lines in backslashes, which I didn't even realise was a language feature until someone randomly suggested trying it to get around the problem. It sure would be nice if Groovy would handle continued lines better... – Hakanai Jul 28 '16 at 04:01