我宁愿用这种丑陋的方式从列表中构建字符串:

val input = listOf("[A,B]", "[C,D]")

val builder = StringBuilder()
builder.append("Serialized('IDs((")
for (pt in input) {
 builder.append(pt[0] + " " + pt[1])
 builder.append(", ")  
}
builder.append("))')")

问题是,它在最后一个元素后添加了一个逗号,如果我想避免,我需要在循环中为最后一个元素添加另一个if check.

I wonder if there is a more concise way of doing this in kotlin?

EDIT

最终结果应该是:

Serialized('IDs((A B,C D))')

推荐答案

在Kotlin中,这种用例可以使用joinToString(它只涉及插入分隔符between个元素).

It is very versatile because it allows to specify a transform function for each element (in addition to the more classic separator, prefix, postfix). This makes it equivalent to mapping all elements to strings and then joining them together, but in one single call.

If input really is a List<List<String>> like you mention in the title and you assume in your loop, you can use:

input.joinToString(
    prefix = "Serialized('IDs((",
    postfix = "))')",
    separator = ", ",
) { (x, y) -> "$x $y" }

注意,带(x, y)的语法是一种解构语法,它会自动获取列表中的第一个和第二个元素(括号很重要).

If your input is in fact a List<String> as in listOf("[A,B]", "[C,D]") that you wrote at the top of your code, you can instead use:

input.joinToString(
    prefix = "Serialized('IDs((",
    postfix = "))')",
    separator = ", ",
) { it.removeSurrounding("[", "]").replace(",", " ") }

Kotlin相关问答推荐

编译后的JavaFX应用程序立即以静默方式崩溃

哪个更好? Integer.valueOf(readLine()) 或 readLine()!!.toInt()

在 Kotlin 中定义基于多态函数的泛型函数

为什么我的通用Kotlin函数中的这个转换未经判断?

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

按钮无法在 Android Studio 上打开新活动

伴随对象在变量更改时更改它的值

如何创建 Kotlin DSL - DSL 语法 Kotlin

如何从 Java 中隐藏 Kotlin 的 lateinit var 支持字段?

Kotlin 解构超过五个组件

Kotlin 中 lambda 表达式中的默认参数

如何在 Kotlin 中使用 volatile

Android Studio 和 Kotlin:Unresolved reference: also

Ktor 在 java.library.path 中没有 netty_transport_native_epoll_x86_64

Kapt不适用于Android Studio 3.0中的AutoValue

如何将map函数应用于Kotlin中的数组并更改其值?

类型不匹配:推断类型为 LoginActivity 但应为 LifecycleOwner

如何在 Gradle Kotlin DSL 中使用来自 gradle.properties 的插件版本?

Kotlin:获取文件的扩展名,例如.txt

Kotlin反射不可用