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?

例如,添加一组字符串:

val text = "This " + "is " + "a " + "long " + "long " + "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"

但是,如果语句的第一行是有效语句,则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.

Kotlin相关问答推荐

如何在Kotlin中反射多个对象以查找特定类型的属性

在Kotlin中将ClosedRange字符串转换为List?<>

Kotlin-elvis算子don';不使用map.get()

在 Kotlin 中将两个字节转换为 UIn16

Criteria Api 中的 Kotlin 泛型

Kotlin 接口类型参数

修改器的属性是什么,我需要更改以使角变圆且宽度更小?喷气背包组合

Kotlin 可空泛型

如何将jooq multiset的结果映射到Hashmap(Java Map)?

如何在 Compose 中创建可重用的修饰符?

jetpack compose 将参数传递给 viewModel

创建首选项屏幕时找不到androidx.preference.PreferenceScreen

如何解决此错误请Kotlin:[Internal Error] java.lang.ExceptionInInitializerError

取消信号上的kotlin流量采集

Kotlin中的测试无法访问受保护(protected)的方法

Android 与 Kotlin - 如何使用 HttpUrlConnection

Kotlin Android:属性委托必须有一个 'getValue(DashViewModel, KProperty*>)' 方法

在 kotlin 中,如何将主构造函数中的属性设置器设为私有?

Kotlin内联属性的用例是什么?

用 kotlin 学习 Android MVVM 架构组件