我怎样才能在 Kotlin 中换行(续行)

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

我有一长行代码,我想分成多行。我使用什么以及语法是什么?

例如添加一串字符串:

val text = "This " + "is " + "a " + "long " + "long " + "line"

Kotlin 中没有续行符号。因为它的语法允许几乎所有符号之间有空格,所以你可以打破语句:

val text = "This " + "is " + "a " +
        "long " + "long " + "line"

但是,如果语句的第一行是有效的语句,它将不起作用:

val text = "This " + "is " + "a "
        + "long " + "long " + "line" // syntax error

为避免在跨多行拆分长语句时出现此类问题,您可以使用括号:

val text = ("This " + "is " + "a "
        + "long " + "long " + "line") // no syntax error

有关详细信息,请参阅 Kotlin Grammar