Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Templates escaping in Kotlin multiline strings

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)

like image 551
ntoskrnl Avatar asked Oct 07 '15 13:10

ntoskrnl


People also ask

How do you escape quotes from Kotlin?

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.

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 you break a line in string with Kotlin?

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 .


2 Answers

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 ... " 
like image 93
Jeremy Lyman Avatar answered Oct 08 '22 04:10

Jeremy Lyman


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.

like image 39
voddan Avatar answered Oct 08 '22 04:10

voddan