我试图在Kotlin中填充一个字符串,以便在控制台输出上实现一些正确的对齐.大致如下:

accountsLoopQuery                             - "$.contactPoints.contactPoints[?(@.contactAccount.id)]"
brokerPassword                                - *****
brokerURI                                     - tcp://localhost:61616
brokerUsername                                - admin
contactPointPriorityProperties                - "contactPointPriority.properties"
customerCollection                            - "customer"
customerHistoryCollection                     - "customer_history"
defaultSystemOwner                            - "TUIGROUP"

I have ended up coding it this way - cheating with Java's String.format:

mutableList.forEach { cp ->
    println(String.format("%-45s - %s", cp.name, cp.value))
}

Is there a proper way to do this with the Kotlin libraries?

推荐答案

你可以用kotlin-stdlib元起的.padEnd(length, padChar = ' ') extension元买这个.它接受所需的length和可选的padChar(默认值为空格):

mutableList.forEach {
    println("${it.name.padEnd(45)} - ${it.value}")
}

There's also padStart that aligns the padding in the other direction.

Kotlin相关问答推荐

如何在Kotlin中为两个数据类创建可重用的方法?

在Kotlin中求n个ClosedRange实例相交的最常用方法是什么?

Scala性状线性化等价于Kotlin

如何让 LocalDateTime.parse 拒绝 24:00 时间

找不到有效的 Docker 环境

用于将 0.5 变为 0 的 round() 函数的模拟

在 kotlin 原始字符串中转义三重引号

Kotlin 协程按顺序执行,但仅在生产机器上执行

在子类中覆盖 kotlin 运算符扩展函数

如何处理基于枚举提前返回的 forEach 循环,Kotlin 中的一条路径除外

Kotlin:内部类如何访问在外部类中声明为参数的变量?

将 Kotlin 类属性设置器作为函数引用

Kapt不适用于Android Studio 3.0中的AutoValue

Kotlin out-projected 类型禁止使用

Lint 错误:可疑的相等判断:在 Object DiffUtilEquals 中未实现 equals()

如何计算Kotlin中的百分比

如何根据ArrayList的对象属性值从中获取最小/最大值?

尾随 lambda 语法(Kotlin)的目的是什么?

你如何在 Kotlin 中注释 Pair 参数?

Kotlin:访问 when 语句的参数