如何在Kotlin字符串模板中嵌入循环

Vad*_*zim 4 string templates loops for-loop kotlin

我们可以很容易地窝表达运营商如ifwhen在科特林字符串模板:

"List ${if (list.isEmpty()) "is empty" else "has ${list.size} items"}."
Run Code Online (Sandbox Code Playgroud)

但是,for或者while不是表达式,不能嵌套在模板中,如下所示:

"<ol>${for (item in list) "<li>$item"}</ol>"
Run Code Online (Sandbox Code Playgroud)

所以我一直在寻找在大型模板中使用循环的方便方法.

Vad*_*zim 5

到目前为止,我发现的最简单的现成方法是用等效的joinToString调用替换循环:

"<ol>${list.joinToString("") { "<li>$it" }}</ol>"
Run Code Online (Sandbox Code Playgroud)

要么

"""
<ol>${list.indices.joinToString("") {
    """
    <li id="item${it + 1}">${list[it]}"""
}}
</ol>""".trimIndent()
Run Code Online (Sandbox Code Playgroud)

出于偏好,还可以使用辅助函数来模拟循环:

inline fun <T> forEach(iterable: Iterable<T>, crossinline out: (v: T) -> String) 
    = iterable.joinToString("") { out(it) }

fun <T> forEachIndexed1(iterable: Iterable<T>, out: (i: Int, v: T) -> String): String {
    val sb = StringBuilder()
    iterable.forEachIndexed { i, it ->
        sb.append(out(i + 1, it))
    }
    return sb.toString()
}
Run Code Online (Sandbox Code Playgroud)

并像这样使用它们:

"<ol>${forEach(list) { "<li>$it" }}</ol>"
Run Code Online (Sandbox Code Playgroud)

要么

"""
<ol>${forEachIndexed1(list) { i, item ->
"""
    <li id="item$i">$item"""
}}
</ol>""".trimIndent()
Run Code Online (Sandbox Code Playgroud)