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

前端 未结 1 914
没有蜡笔的小新
没有蜡笔的小新 2021-01-08 00:35

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:



        
相关标签:
1条回答
  • 2021-01-08 01:04

    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.

    0 讨论(0)
提交回复
热议问题