swiftstringkotlinstring-formatting

Kotlin equivalent of %@ in swift


i am new to kotlin. In swift i can do :

let endpoint = "categories/" + "%@/issues/"
let number = "4"
let finalstring = String(format: endpoint, number)

The final output of the string will be : categories/4/issues/ as a string .

I have looked at string format in kotlin but it's only work afterwards meaning that i can't define a template for my string and fill it later.

var value1 = "categories/"
var value2 = 4
var value3 = "/issues/"
println(java.lang.String.format("%s%d%s", value1, value2, value3))

This give me the same result but it's mean that i have to manualy write the end of the string.

What i want to do i to have a template for my string in a Road file. Then complet my string at the run time. The probleme is that the part of my string that i want to complete is in the middle of the string. Of course i can use substring and remplace but i am looking for a clean way to do it as in swift.

Thanks for helping.


Solution

  • You can create your format string up front with all the constant parts, and with relevant placeholders (like %d for numbers) (more info in the javadoc).

    Later, use the regular Java String.format() later with the parameters:

    // define this constant up front
    val format = "categories/%d/issues/"
    
    // and then later:
    val categoryId = 4
    println(String.format(format, categoryId))