Templates escaping in Kotlin multiline strings

If I want to use $ sign in multiline strings, how do I escape it?

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

$eq is parsed as a reference to a variable. How to escape $, so that it will not be recognized as reference to variable? (Kotlin M13)


Solution 1:

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

Solution 2:

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.

Solution 3:

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