Search code examples
stringkotlinescaping

How to use dollar sign '$' in raw (multiline) Kotlin strings?


Is there a concise way to escape $ character in a raw Kotlin string?

In a simple string we use "\$".
In a raw string there is obviuous but superabundant way """${"$"}""" that does not work good when the string contains lot of $, i.e. in MongoDB query or some kind of third-party library template.


Solution

  • for mongo operators you can define constants to avoid this problem, smth like that

    object MongoOperators {
        const val eq = "\$eq"
        const val ne = "\$ne"
        const val and = "\$and"
    }
    
    val findFilter = """
            {
                $and: [
                   "foo": { $eq : 1},
                   "bar": { $ne : 2}
                ]
            }
        """.trimIndent()