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

标签 string loops templates for-loop kotlin

我们可以很容易地嵌套表达式运算符,如 ifwhen在 Kotlin 字符串模板中:

"List ${if (list.isEmpty()) "is empty" else "has ${list.size} items"}."

但是forwhile不是表达式,不能像这样嵌套在模板中:
"<ol>${for (item in list) "<li>$item"}</ol>"

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

最佳答案

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

"<ol>${list.joinToString("") { "<li>$it" }}</ol>"

或者
"""
<ol>${list.indices.joinToString("") {
    """
    <li id="item${it + 1}">${list[it]}"""
}}
</ol>""".trimIndent()

在偏好方面,也可以使用辅助函数模拟循环:
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()
}

并像这样使用它们:
"<ol>${forEach(list) { "<li>$it" }}</ol>"

或者
"""
<ol>${forEachIndexed1(list) { i, item ->
"""
    <li id="item$i">$item"""
}}
</ol>""".trimIndent()

关于string - 如何在 Kotlin 字符串模板中嵌入 for 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44554781/

相关文章:

java - Java中字符串的最大长度-调用length()方法

Python - 非常基础 'encryptor'

Python unicode 正则表达式不适用于大字符串

带有菜单功能的 Python 主函数循环不起作用?

javascript - 如何将这些重复的 JavaScript 代码缩短为循环?

javascript - 使用 Express JS 的 Angular 模板组件

模板中的 C++ 数据类型

Javascript 替换并 $ 符号在 newSubStr 中

c++ for循环中的简单求和

c++ - SFINAE 检查继承的成员函数