I was trying to pad a string in Kotlin to achieve some proper alignment on the console output. Something along these lines:
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?
String interpolation is variable substitution with its value inside a string. In Kotlin, we use the $ character to interpolate a variable and ${} to interpolate an expression. Kotlin string formatting is more powerful than basic interpolation.
Kotlin strings are mostly similar to Java strings but has some new added functionalities. Kotlin strings are also immutable in nature means we can not change elements and length of the String. To declare a string in Kotlin, we need to use double quotes(” “), single quotes are not allowed to define Strings.
Using trim() function The standard solution to trim a string is using the trim() function. Since the string is immutable in Kotlin, it returns a new string having leading and trailing whitespace removed. To just remove the leading whitespaces, use the trimStart() function.
You can use the .padEnd(length, padChar = ' ')
extension from kotlin-stdlib
for that. It accepts the desired length
and an optional padChar
(default is whitespace):
mutableList.forEach {
println("${it.name.padEnd(45)} - ${it.value}")
}
There's also padStart
that aligns the padding in the other direction.
You can using String#format extension function instead, In fact, it is inlined to call-site function with java.lang.String#format for example:
mutableList.forEach { cp ->
println("%-45s - %s".format(cp.name, cp.value))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With