在字符串文字中转义字符串插值

Escape String interpolation in a string literal

在普通字符串中,我可以用反斜杠转义 ${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."""

根据 String templates docs,您可以直接在原始字符串中表示 $

Templates are supported both inside raw strings and inside escaped strings. If you need to represent a literal $ character in a raw string (which doesn't support backslash escaping), you can use the following syntax:

val text = """This ${'$'}{variable} will be substituted."""
println(text) // This ${variable} will be substituted.

来自kotlinlang.org

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

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

所以,在你的情况下:

"""This ${'$'}{variable} will not be substituted."""