You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何格式化Kotlin中List内包含Set记录的Alert数据类的输出

你可以直接对records集合调用joinToString方法,自定义元素格式、前后缀即可,不需要依赖默认的toString()输出。

修改后的完整代码

val orderedStatuses = getOrderedStatuses(date, statuses)
val alert = if (orderedStatuses.isEmpty()) {
    "No alerts found"
} else {
    "${orderedStatuses.size} alerts found " +
        "Alerts:\n" +
        orderedStatuses.joinToString("\n") {
            "\t${it.status} : \n" +
                "\t${it.records.joinToString(separator = ", ", prefix = "(", postfix = ")") { record -> "'$record'" }}"
        }
}

复用优化(可选)

如果多个地方需要用到这个格式,可以抽取成扩展函数简化调用:

// 扩展函数定义,可放在全局公共位置
fun Set<String>.toFormattedAlertRecords(): String {
    return joinToString(separator = ", ", prefix = "(", postfix = ")") { "'$it'" }
}

// 调用处简化写法
val orderedStatuses = getOrderedStatuses(date, statuses)
val alert = if (orderedStatuses.isEmpty()) {
    "No alerts found"
} else {
    "${orderedStatuses.size} alerts found " +
        "Alerts:\n" +
        orderedStatuses.joinToString("\n") {
            "\t${it.status} : \n" +
                "\t${it.records.toFormattedAlertRecords()}"
        }
}

内容的提问来源于stack exchange,提问作者AnthonyEdwardsStan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 00:15:03