4

在普通字符串中,我可以${variable}用反斜杠转义:

"You can use \${variable} syntax in Kotlin."

是否可以在字符串文字中做同样的事情?反斜杠不再是转义字符:

// Undesired: Produces "This \something will be substituted.
"""This \${variable} will be substituted."""

到目前为止,我看到的唯一解决方案是字符串连接,这非常难看,以及嵌套插值,这开始变得有点荒谬:

// Desired: Produces "This ${variable} will not be substituted."
"""This ${"\${variable}"} will not be substituted."""
4

2 回答 2

6

来自kotlinlang.org

如果您需要在原始字符串中表示文字 $ 字符(不支持反斜杠转义),您可以使用以下语法:

val price = """
${'$'}9.99
"""

所以,在你的情况下:

"""This ${'$'}{variable} will not be substituted."""
于 2020-01-03T10:46:03.177 回答
5

根据字符串模板文档,您可以$直接在原始字符串中表示:

原始字符串和转义字符串都支持模板。如果您需要在原始字符串中表示文字 $ 字符(不支持反斜杠转义),您可以使用以下语法:

val text = """This ${'$'}{variable} will be substituted."""
println(text) // This ${variable} will be substituted.
于 2020-01-03T10:44:50.910 回答