I've got a String template looking like this:
val template = "Something %s something else %s. The first was %1$s, the second was %2$s"
works fine with Java. How do I use this reoccurring String values with Kotlin?
Looks like %1$s is not possible.
Compiler warning: unresolved reference: s
String literals in Kotlin are capable of string interpolation, and the dollar sign is the start of a string template expression. If you need the literal dollar sign in a string instead, you should escape it using a backslash: \$. So your template (which I assume you're passing to String.format) becomes:
val template = "Something %s something else %s. The first was %1\$s, the second was %2\$s"
As Alexander Udalov's answer say, $ can be used for String Templates.
Apart from use backslash to escape the char $, you also can use ${'$'} to escape it. This syntax will be more useful when you want to escape the $ in a raw string, where backslash escaping is not supported.
val template = "Something %s something else %s. The first was %1${'$'}s, the second was %2${'$'}s"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With