2

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

2 Answers 2

5

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"
Sign up to request clarification or add additional context in comments.

Comments

5

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"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.