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

Dru*_*les 4 string-literals string-interpolation kotlin

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

"You can use \${variable} syntax in Kotlin."
Run Code Online (Sandbox Code Playgroud)

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

// Undesired: Produces "This \something will be substituted.
"""This \${variable} will be substituted."""
Run Code Online (Sandbox Code Playgroud)

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

// Desired: Produces "This ${variable} will not be substituted."
"""This ${"\${variable}"} will not be substituted."""
Run Code Online (Sandbox Code Playgroud)

Maf*_*for 6

来自kotlinlang.org

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

val price = """
${'$'}9.99
"""
Run Code Online (Sandbox Code Playgroud)

所以,在你的情况下:

"""This ${'$'}{variable} will not be substituted."""
Run Code Online (Sandbox Code Playgroud)


Kar*_*cki 5

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

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

val text = """This ${'$'}{variable} will be substituted."""
println(text) // This ${variable} will be substituted.
Run Code Online (Sandbox Code Playgroud)