'Kotlin string escape special char: $

This is my scratch:

// how to present $-$ as Kotlin string
val var1 = "\$-\$"
val var2 = "\$-$"

print("${var1.count()}: $var1")
print("${var2.count()}: $var2")

print("${var1 == var2}")

enter image description here can someone explain why var2 works? (no need to escape 2nd $ char?)



Solution 1:[1]

A template expression in a template String in Kotlin is a dollar ($) followed by either a name or an expression in curly braces (see the String templates documentation).

The single $ sign which is followed by nothing in your String var2 does not need to be escaped because it is not a template expression.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Karsten Gabriel