I have a long line of code that I want to break up among multiple lines. What do I use and what is the syntax?
For example, adding a bunch of strings:
val text = "This " + "is " + "a " + "long " + "long " + "line"
To split a string on newlines, we can use the regular expression \r?\ n|\r which matches with all different line terminator i.e., \r\n , \r , and \n . To skip empty lines, we can change the regular expression to [\r\n]+ . To match with any Unicode linebreak sequence, we can use the linebreak matcher \R .
Inserting a newline code \n , \r\n into a string will result in a line break at that location. On Unix, including Mac, \n (LF) is often used, and on Windows, \r\n (CR + LF) is often used as a newline code.
A line break ends the line you are currently on and resumes on the next line. Placing <br /> within the code is the same as pressing the return key in a word processor. Use the <br /> tag within the <p> (paragraph) tag.
You cannot split a statement into multiple lines in Python by pressing Enter . Instead, use the backslash ( \ ) to indicate that a statement is continued on the next line.
There is no symbol for line continuation in Kotlin. As its grammar allows spaces between almost all symbols, you can just break the statement:
val text = "This " + "is " + "a " +
"long " + "long " + "line"
However, if the first line of the statement is a valid statement, it won't work:
val text = "This " + "is " + "a "
+ "long " + "long " + "line" // syntax error
To avoid such issues when breaking long statements across multiple lines you can use parentheses:
val text = ("This " + "is " + "a "
+ "long " + "long " + "line") // no syntax error
For more information, see Kotlin Grammar.
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