Java String.format alternative in kotlin?

Hi,

I’m using java String.format in my codes which i want to port to kotlin.
For example
String log = String.format(“%d, %s, %6f : %3f”, value1, value2, value3, value4)

How to convert above java code to kotlin?

Thanks

3 Likes

You can use java String

fun main(args : Array<String>) {   var value1 = 1   var value2 = "2"   var value3 = 3.0   var value4 = 4.0   println(java.lang.String.format("%d, %s, %6f : %3f", value1, value2, value3, value4)) }

Thank you for your reply. It works.

1 Like

You can also write

println(“%d, %s, %6f : %3f”.format(value1, value2, value3, value4))

10 Likes

This has limitation that it works only in JVM compilation target (not in JS or native).

5 Likes

I’ve created a simple drop-in replacement library to have subset of String.format() features in pure Kotlin. Check it out here https://github.com/Simplx-dev/kotlin-format

4 Likes

Hi @B7W!
I think that in this form, is better than using java.lang.String.format("%d, %s, %6f : %3f", value1, value2, value3, value4).
Am I right?

Hi!

"String.format"is idiomatic way for Kotlin to format string.
And it is just sugar.

public inline fun String.format(vararg args: Any?): String = java.lang.String.format(this, *args)

2 Likes

Simple

println(“$value1, $value2, $value3 : $value4”)

Just bumping this thread, is bodia’s library still the best option for multiplatform Kotlin libraries?

4 Likes