Where can I find documentation on Kotlin <string f...
# getting-started
m
Where can I find documentation on Kotlin string formatting? I found a python equivalent of what I want here, but I can’t for the life of me find anything for Kotlin
c
to round this out - Kotlin supports string interpolation to handle a lot of “formatting” use cases, with the Formatter class (or other custom code) to handle specific cases. I personally rarely use Formatter, though can see use cases where that would be required.
🙏 1
c
And when string interpolation is not powerful enough, buildString is your friend:
Copy code
val str = buildString {
    append("First line")

    if (someCondition)
        append("\nSecond line")

    for (l in lines)
        append("\n$l")
}
j
Yes, string interpolation is nice for embedding variable parts into an otherwise fixed string,
buildString
is the next level for conditionally concatenate parts of text, but there is still a need for actual formatting with things like
String.format
for decimal numbers for instance. These convenience extensions for dealing with format strings in Kotlin indeed rely on Java's format strings defined in the
Formatter
class: https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Formatter.html
k
While Java offers
String.format("%.3f%n", PI)
, Kotlin offers a convenience extension function so that you can do
"%.3f%n".format(PI)"
. Documented at https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.text/format.html but unfortunately doesn't specify the format string semantics. It should have at least mentioned it's the same as Java's.
2