Dollar Sign Character in Strings

StringTemplatesKotlin

String Problem Overview


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.

String Solutions


Solution 1 - String

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 - String

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 - String

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.

Solution 4 - String

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)

Solution 5 - String

For Kotlin developers.

What I wanted to do was this:

val $name : String

If that's your case too, use this:

val `$name` : String

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTravisView Question on Stackoverflow
Solution 1 - StringAlexander UdalovView Answer on Stackoverflow
Solution 2 - Stringkojow7View Answer on Stackoverflow
Solution 3 - StringJayson MinardView Answer on Stackoverflow
Solution 4 - StringBlundellView Answer on Stackoverflow
Solution 5 - StringGilbertSView Answer on Stackoverflow