格式Kotlin字符串多次出现

我有一个字符串模板看起来像这样:

val template = "Something %s something else %s. The first was %1$s, the second was %2$s" 

与Java一起工作良好。 如何与Kotlin一起使用这个反复出现的字符串值? 看起来像%1$s是不可能的。

编译器警告: unresolved reference: s

Kotlin中的字符串文字能够进行字符串插值,美元符号是字符串模板expression式的开始。 如果您需要在字符串中使用字面美元符号,则应使用反斜线: \$进行转义。 所以你的模板(我假设你传递给String.format )变成:

 val template = "Something %s something else %s. The first was %1\$s, the second was %2\$s" 

正如Alexander Udalov的回答所说, $可以用于字符串模板 。

除了使用反斜线来转义char $ ,还可以使用${'$'}来转义它。 当您想要在原始字符串中转义$时,此语法将更加有用,不支持反斜杠转义。

 val template = "Something %s something else %s. The first was %1${'$'}s, the second was %2${'$'}s"