Templates escaping in Kotlin multiline strings

StringKotlinSyntax

String Problem Overview


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)

String Solutions


Solution 1 - String

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 - String

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 - String

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionntoskrnlView Question on Stackoverflow
Solution 1 - StringJeremy LymanView Answer on Stackoverflow
Solution 2 - StringvoddanView Answer on Stackoverflow
Solution 3 - StringYona AppletreeView Answer on Stackoverflow