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

2

33

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"
Kurrajong answered 25/5, 2017 at 12:28 Comment(1)
for breaking line you can use \nNielsen
K
59

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.

Kurrajong answered 25/5, 2017 at 12:28 Comment(4)
This doesn't seem to work in return statements, for example return "a" + \n "b" will just return a.Dignify
my mistake, the actual problem was return a ?: "" + \n "b" will return just aDignify
I often see line breaks before the dot operator even when the line is a valid statement: let foo = obj <\n> . do() .. Any hint how to see in the grammar that this is allowed?Prelude
Found an answer: #73576323Prelude
D
1

Another approach is to go for the 3 double quotes "" pairs i.e. press the double quotes 3 times to have something like this.

val text = """
    
    This is a long 
    long
    long
    line
""".trimIndent()

With this approach you don't have to use + , \n or escape anything; just please Enter to put the string in the next line.

trimIndent() to format multi-line strings - Detects a common minimal indent of all the input lines, removes it from every line and also removes the first and the last lines if they are blank (notice difference blank vs empty).

Dux answered 1/11, 2022 at 17:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.