在 Kotlin 多行字符串中转义的模板

Templates escaping in Kotlin multiline strings

如果我想在多行字符串中使用 $ 登录,我该如何转义它?

val condition = """ ... $eq ... """

$eq 被解析为对变量的引用。如何转义$,使其不被识别为对变量的引用? (科特林 M13)

来自documentation

A raw string is delimited by a triple quote ("""), contains no escaping and can contain newlines and any other character

您需要使用带换行符的标准字符串

" ...\n $eq \n ... "

或者您可以使用文字表示

""" ... ${'$'}eq ... "

有趣,但行得通:

val eq = "$eq"

print("""... $eq  ..."""")   // just like you asked :D

实际上,如果 eq 是一个数字(价格或某物),那么您可能想要单独计算它,并且按照我的建议进行额外的外部计算不会有什么坏处。

如果你提前知道你想要什么 $-变量(比如在查询 Mongo 时,看起来你可能正在做),你可以创建一个小帮手定义这些变量的对象。您还可以获得一些保护,防止意外拼错您的操作员之一,这很好。

object MongoString {
    inline operator fun invoke(callback: MongoString.() -> String) = callback()

    val eq = "$eq"
    val lt = "$lt"
    // ... and all the other operators ...
}

fun test() {
    val query = MongoString { """{"foo": {$lt: 10}}""" }
}

我在这里为 mongo 编写了更新和查询字符串的简单版本:https://gist.github.com/Yona-Appletree/29be816ca74a0d93cdf9e6f5e23dda15