【发布时间】:2015-08-21 19:58:20
【问题描述】:
在字符串文字中添加$ 字符的最简洁方法是什么?
目前为止我想出的最佳解决方案是"""${"$"}...""",我觉得它很难看。
【问题讨论】:
在字符串文字中添加$ 字符的最简洁方法是什么?
目前为止我想出的最佳解决方案是"""${"$"}...""",我觉得它很难看。
【问题讨论】:
要在字符串文字中转义美元符号,请使用反斜杠字符:
"\$"
要在 raw 字符串文字 ("""...""") 中转义它,您提供的解决方法确实是目前最简单的解决方案。错误跟踪器中有一个问题,您可以为它加注星标和/或投票:KT-2425。
【讨论】:
您似乎没有正确粘贴代码,因为您只有 3 个双引号。
无论如何,最好的方法就是将美元符号转义如下:
"\$"
【讨论】:
在当前的 Kotlin 1.0(和测试版)中你可以用反斜杠 "\$" 转义
这个通过的单元测试证明了案例:
@Test public fun testDollar() {
val dollar = '$'
val x1 = "\$100.00"
val x2 = "${"$"}100.00"
val x3 = """${"$"}100.00"""
val x4 = "${dollar}100.00"
val x5 = """${dollar}100.00"""
assertEquals(x5, x1)
assertEquals(x5, x2)
assertEquals(x5, x3)
assertEquals(x5, x4)
// you cannot backslash escape in """ strings, therefore:
val odd = """\$100.00""" // creates "\$100.00" instead of "$100.00"
// assertEquals(x5, odd) would fail
}
所有版本都创建一个字符串"$100.00",除了最后一个奇怪的情况。
【讨论】:
要在多行字符串中显示文字美元符号,您可以执行以下操作
我为我的罪感到抱歉:
val nonInterpedValue = "\${someTemplate}"
val multiLineWithNoninterp = """
Hello
$nonInterpedValue
World
""".trimIndent()
正如在其他地方提到的,这是解决方法,因为现在您不能在多行字符串中使用美元符号。 https://youtrack.jetbrains.com/issue/KT-2425
(我需要这个来让 Groovy 的模板引擎工作:https://www.baeldung.com/groovy-template-engines)
【讨论】:
对于 Kotlin 开发人员。
我想做的是:
val $name : String
如果你也是这种情况,请使用:
val `$name` : String
【讨论】: