Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Padding string in Kotlin

Tags:

kotlin

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?

like image 333
gil.fernandes Avatar asked Jul 25 '17 17:07

gil.fernandes


People also ask

What is ${} in Kotlin?

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.

How do you manipulate string in Kotlin?

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.

How do you trim strings in Kotlin?

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.


2 Answers

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.

like image 194
hotkey Avatar answered Sep 17 '22 17:09

hotkey


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))
}
like image 42
holi-java Avatar answered Sep 21 '22 17:09

holi-java