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)
Escaped string is declared within double quote (" ") and may contain escape characters like '\n', '\t', '\b' etc. Raw string is declared within triple quote (""" """) and may contain multiple lines of text without any escape characters.
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.
The split() function is often used to split a string around matches of a regular expression. To split a string on newlines, we can use the regular expression \r?\ n|\r which matches with all different line terminator i.e., \r\n , \r , and \n .
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 ... "
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With