英文:
Escape String interpolation in a string literal
问题
"在普通字符串中,我可以用反斜杠来转义${variable}
:
"你可以在Kotlin中使用${variable}语法。"
在字符串字面值中是否也可以这样做?反斜杠不再是转义字符:
// 不期望的结果:生成"This \something将被替换。
"""This ${variable}将被替换。"""
到目前为止,我看到的唯一解决方案是字符串连接,这实在太丑陋了,还有嵌套插值,这开始变得有点荒谬:
// 期望的结果:生成"This ${variable}不会被替换。"
"""This ${"${variable}"}不会被替换。"""
英文:
In a normal String I can escape the ${variable}
with a backslash:
"You can use ${variable} syntax in Kotlin."
Is it possible to do the same in a String literal? The backslash is no longer an escape character:
// Undesired: Produces "This \something will be substituted.
"""This ${variable} will be substituted."""
So far, the only solutions I see are String concatenation, which is terribly ugly, and nesting the interpolation, which starts to get a bit ridiculous:
// Desired: Produces "This ${variable} will not be substituted."
"""This ${"${variable}"} will not be substituted."""
答案1
得分: 6
如果您需要在原始字符串(不支持反斜杠转义)中表示字面$字符,您可以使用以下语法:
val price = """
${'$'}9.99
"""
所以,在您的情况下:
"""This ${'$'}{variable} will not be substituted."""
英文:
From kotlinlang.org:
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 price = """
${'$'}9.99
"""
So, in your case:
"""This ${'$'}{variable} will not be substituted."""
答案2
得分: 5
根据String templates docs,您可以直接在原始字符串中表示$
:
> 模板支持原始字符串和转义字符串中的使用。如果您需要在原始字符串中表示文字 $
字符(它不支持反斜杠转义),您可以使用以下语法:
val text = """This ${'$'}{variable} will be substituted."""
println(text) // This ${variable} will be substituted.
英文:
As per String templates docs you can represent the $
directly in a raw string:
> 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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论