Dollar Sign Character in Strings

Solution 1:

To escape the dollar sign inside a string literal, use the backslash character:

"\$"

To escape it in a raw string literal ("""..."""), the workaround you provided is indeed the easiest solution at the moment. There's an issue in the bug tracker, which you can star and/or vote for: KT-2425.

Solution 2:

It doesn't look like you pasted your code correctly as you only have 3 double quotes.

Anyhow, the best way to do this is to just escape the dollar sign as follows:

"\$"

Solution 3:

In current Kotlin 1.0 (and betas) you can just escape with backslash "\$"

This passing unit test proves the cases:

@Test public fun testDollar() {
    val dollar = '$'

    val x1 = "\$100.00"
    val x2 = "${"$"}100.00"
    val x3 = """${"$"}100.00"""
    val x4 = "${dollar}100.00"
    val x5 = """${dollar}100.00"""

    assertEquals(x5, x1)
    assertEquals(x5, x2)
    assertEquals(x5, x3)
    assertEquals(x5, x4)

    // you cannot backslash escape in """ strings, therefore:

    val odd = """\$100.00""" // creates "\$100.00" instead of "$100.00"
    // assertEquals(x5, odd) would fail
}

All versions make a string "$100.00" except for the one odd case at the end.