Is there a brief way in Kotlin to build formatted strings with variables, similar to f-strings in Python? For example:
f'My cat is {weight:.1f} pounds.'
Which would yield:
My cat is 25.3 pounds.
Is there a brief way in Kotlin to build formatted strings with variables, similar to f-strings in Python? For example:
f'My cat is {weight:.1f} pounds.'
Which would yield:
My cat is 25.3 pounds.
The usual way to do this is with String.format()
.
It's also an extension method on String
, so you can call it as follows:
"My cat is %.1f pounds.".format(weight)
For details, see this question; the docs for the format patterns are here. (Both are for the Java version, but it's the same in Kotlin.)
As there was no good and multiplatform tool, I wrote MP library that implements a traditional printf
-like formatting. It is used in many projects, it is simple and works everywhere the same (.format
worked on JVM only - at least at the time I wrote the library):