Templates escaping in Kotlin multiline strings
Funny, but that works:
val eq = "\$eq"
print("""... $eq ..."""") // just like you asked :D
Actually, if eq
is a number (a price, or sth), then you probably want to calculate it separately, and an additional external calculation as I suggested won't hurt.
From the documentation
A raw string is delimited by a triple quote ("""), contains no escaping and can contain newlines and any other character
You would need to use a standard string with newlines
" ...\n \$eq \n ... "
or you could use the literal representation
""" ... ${'$'}eq ... "
In the case where you know ahead of time what $
-variables you want (like when querying Mongo, as it looks like you might be doing), you can create a little helper object that defines those variables. You also get some protection against accidentally misspelling one of your operators, which is neat.
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}}""" }
}
I wrote simple versions for update and query strings for mongo here: https://gist.github.com/Yona-Appletree/29be816ca74a0d93cdf9e6f5e23dda15