Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format Kotlin String with multiple occurrences

Tags:

string

kotlin

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

like image 454
Rico Avatar asked Jan 18 '26 15:01

Rico


2 Answers

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"
like image 85
Alexander Udalov Avatar answered Jan 21 '26 06:01

Alexander Udalov


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"
like image 22
LF00 Avatar answered Jan 21 '26 06:01

LF00