Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape String interpolation in a string literal

In a normal String I can escape the ${variable} with a backslash:

"You can use \${variable} syntax in Kotlin."

Is it possible to do the same in a String literal? The backslash is no longer an escape character:

// Undesired: Produces "This \something will be substituted.
"""This \${variable} will be substituted."""

So far, the only solutions I see are String concatenation, which is terribly ugly, and nesting the interpolation, which starts to get a bit ridiculous:

// Desired: Produces "This ${variable} will not be substituted."
"""This ${"\${variable}"} will not be substituted."""
like image 435
Druckles Avatar asked Dec 18 '22 14:12

Druckles


2 Answers

From kotlinlang.org:

If you need to represent a literal $ character in a raw string (which doesn't support backslash escaping), you can use the following syntax:

val price = """
${'$'}9.99
"""

So, in your case:

"""This ${'$'}{variable} will not be substituted."""
like image 159
Mafor Avatar answered Dec 30 '22 11:12

Mafor


As per String templates docs you can represent the $ directly in a raw string:

Templates are supported both inside raw strings and inside escaped strings. If you need to represent a literal $ character in a raw string (which doesn't support backslash escaping), you can use the following syntax:

val text = """This ${'$'}{variable} will be substituted."""
println(text) // This ${variable} will be substituted.
like image 36
Karol Dowbecki Avatar answered Dec 30 '22 09:12

Karol Dowbecki