Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I do a line break (line continuation) in Kotlin

Tags:

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"
like image 501
bryant1410 Avatar asked May 25 '17 12:05

bryant1410


People also ask

How do you add a line break in Kotlin?

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 .

How do you put a line break inside a string?

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.

How do you break a code line?

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.

How do you continue on the next line in Python?

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.


1 Answers

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.

like image 54
bryant1410 Avatar answered Sep 28 '22 07:09

bryant1410