在字符串字面量中避免字符串插值

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."""

1
当你有这样的问题(无论是哪种语言)时,我建议你使用类似 https://play.kotlinlang.org/ 的工具。 - Ivan Kaloyanov
你能解释一下“such a question”是什么意思吗? - Druckles
当然,我的意思是指可以在一两秒钟内测试/重现的东西 :) - Ivan Kaloyanov
确切的期望输出是什么?是 "This \something will be substituted." 还是 "This ${variable} will not be substituted." - deHaar
2
@deHaar 后者。 - Druckles
一个简单的解决方案是在 ${ 之间添加一个空格,这样不会影响格式。 - Harshvardhan Joshi
2个回答

6

来自kotlinlang.org

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

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

所以,在您的情况下:

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

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

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接