What is the cleanest method for adding a $ character in a string literal?
The best solution I've come up with so far is """${"$"}...""", which looks ugly to me.
What is the cleanest method for adding a $ character in a string literal?
The best solution I've come up with so far is """${"$"}...""", which looks ugly to me.
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.
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.
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:
"\$"
To get literal dollar signs shows in multi-line strings, you can do the below
I'm sorry for my sins:
val nonInterpedValue = "\${someTemplate}"
val multiLineWithNoninterp = """
        Hello
        $nonInterpedValue
        World
""".trimIndent()
As mentioned elsewhere, this is the workaround because right now you can't use dollar signs inside multi-line strings. https://youtrack.jetbrains.com/issue/KT-2425
( I needed this to get Groovy's Template Engine working: https://www.baeldung.com/groovy-template-engines)
For Kotlin developers.
What I wanted to do was this:
val $name : String
If that's your case too, use this:
val `$name` : String