在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(",", " ") }