Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Escape ${something} in a Kotlin String

Tags:

kotlin

What is the correct way of defining a Kotlin string that includes the characters for declaring a template substitution, but not have this evaluated as a template?

For example: "${something}" just treated as an ordinary string.

I would like to use the Spring value annotation:

@Value("${some.property}) lateinit var foobar : String? 
like image 241
Jasper Blues Avatar asked Nov 01 '15 10:11

Jasper Blues


People also ask

How do I escape a character in a string?

To insert characters that are illegal in a string, use an escape character. An escape character is a backslash \ followed by the character you want to insert.

What is ${} in Kotlin?

Kotlin string interpolation String interpolation is variable substitution with its value inside a string. In Kotlin, we use the $ character to interpolate a variable and ${} to interpolate an expression.

How do I ignore an escape character in a string?

To ignoring escape sequences in the string, we make the string as "raw string" by placing "r" before the string. "raw string" prints as it assigned to the string. Python | How to print double quotes with the string variable?


1 Answers

This works for me:

val s = "\${foo}" println("s = ${s}") // prints s = ${foo} 

The documented way also works fine:

val s = "${'$'}{foo}" println("s = ${s}") // prints s = ${foo} 
like image 136
JB Nizet Avatar answered Sep 27 '22 21:09

JB Nizet